package com.zbkj.crmeb.merchant.admin.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.Resource;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.crmeb.core.config.MybatisPlusConfig;
import com.utils.*;
import com.utils.dto.StoreProductDto;
import com.utils.dto.StoreProductQueryDto;
import com.zbkj.crmeb.enums.*;
import com.zbkj.crmeb.enums.plat.PlatPushStatusEnums;
import com.zbkj.crmeb.export.vo.StoreAdminProductExcelVo;
import com.zbkj.crmeb.merchant.admin.service.StoreProductStockService;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.dto.product.StoreProductQueryDTO;
import com.zbkj.crmeb.store.intercept.RateLimiter;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.service.*;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.annotation.UnitConvertUtil;
import com.crmeb.core.exception.CrmebException;
import com.crmeb.core.utils.RedisUtil;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.category.model.Category;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelDiscount;
import com.zbkj.crmeb.chant.model.ChannelDiscountGoods;
import com.zbkj.crmeb.chant.model.ChannelMemberLevel;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ChannelDiscountGoodsService;
import com.zbkj.crmeb.chant.service.ChannelDiscountService;
import com.zbkj.crmeb.chant.service.ChannelMemberLevelService;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.export.vo.ProductExcelVo;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.vo.RatioVo;
import com.zbkj.crmeb.marketing.dto.CouponProductRangeDTO;
import com.zbkj.crmeb.marketing.model.StoreCouponUser;
import com.zbkj.crmeb.member.enums.EquityTypeEnum;
import com.zbkj.crmeb.member.model.MerchantMemberBenefits;
import com.zbkj.crmeb.member.model.StoreProductDiscount;
import com.zbkj.crmeb.member.service.IMerchantMemberBenefitsService;
import com.zbkj.crmeb.member.service.IStoreProductDiscountService;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.merchant.api.service.FrontCouponUserService;
import com.zbkj.crmeb.store.dao.StoreProductAttrValueDao;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dao.StoreProductNormDao;
import com.zbkj.crmeb.store.request.MarkupRateRequest;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductRequest;
import com.zbkj.crmeb.store.request.StoreProductSearchRequest;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.StoreProductTabsHeader;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.system.service.SystemAttachmentService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Mr.Zhang
 * @description StoreProductServiceImpl 接口实现
 * @date 2020-05-27
 */
@Slf4j
@Service
public class MerStoreProductServiceImpl extends ServiceImpl<StoreProductDao, StoreProduct> implements MerStoreProductService {
    @Autowired
    PriceUtil priceUtil;
    @Resource
    private StoreProductDao storeProductDAO;
    @Resource
    private StoreProductNormDao storeProductNormDAO;
    @Resource
    private StoreProductAttrValueDao storeProductAttrValueDAO;
    @Autowired
    private StoreProductAttrService attrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductCateService storeProductCateService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StoreProductRelationService storeProductRelationService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private StoreProductCouponService storeProductCouponService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private MarkupRateService markupRateService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private ProductUtil productUtil;
    @Resource
    private StoreProductMerService storeProductMerService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private StoreZoneProductService storeZoneProductService;
    @Autowired
    private StoreZoneService storeZoneService;
    @Autowired
    private SystemAdminService systesmAdminService;
    @Autowired
    private FrontCouponUserService frontCouponUserService;
    @Autowired
    private StoreProductNormDescriptionService storeProductNormDescriptionService;
    @Autowired
    private ProductConvertUtil productConvertUtil;
    @Autowired
    private IStoreProductDiscountService storeProductDiscountService;
    @Autowired
    private IMerchantMemberBenefitsService merchantMemberBenefitsService;
    @Autowired
    private ChannelMemberLevelService channelMemberLevelService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductDraftService storeProductDraftService;
    @Autowired
    private StoreProductAttrValueDraftService storeProductAttrValueDraftService;
    @Autowired
    private StoreProductUploadService storeProductUploadService;
    @Resource
    private ChannelDiscountService channelDiscountService;
    @Resource
    private ChannelDiscountGoodsService channelDiscountGoodsService;
    @Autowired
    private StoreCartService storeCartService;
    @Resource
    private RelationService relationService;
    @Autowired
    StoreProductStockService storeProductStockService;
    @Autowired
    StoreProductValueMerService storeProductValueMerService;
    @Autowired
    private ChannelFreeShippingActivityService channelFreeShippingActivityService;


    private final static ExecutorService executorService = ThreadPoolUtils.getThread();

    /**
     * 新增产品
     *
     * @param storeProductRequest 新增产品request对象
     * @return 新增结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(StoreProductRequest storeProductRequest) {
        if (!redisUtil.lock(RedisUtil.PRODUCT_BARCODE_LOCK, "product", 1L)) {
            return false;
        }
        log.info("--------------- {}新增自建商品: {} ---------------", systesmAdminService.getAdminId(), JSON.toJSONString(storeProductRequest));
        //设置barCode
        StoreBrand storeBrand = storeBrandService.getById(storeProductRequest.getBrandId());
        storeProductRequest.setBarCode(getProductBarCode(storeProductRequest.getMerId()));
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductRequest, storeProduct, "degree");
        //storeProduct.setIsShow(true);
        storeProduct.setCreateTime(new Date());
        if (null != storeBrand) {
            storeProduct.setBrandName(storeBrand.getEnName());
        }
        if (StrUtil.isEmpty(storeProduct.getSyncKeyword())) {
            storeProduct.setSyncKeyword(storeProductRequest.getKeyword());
        }
        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));
        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));

        // 获取 attrValue 字符串 解析后对应attrValue表中的数据
        //        List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = getStoreProductAttrValueRequests(storeProductRequest);
        if (BooleanUtils.isTrue(storeProductRequest.getSecondhand())) {
            if (StringUtils.isBlank(storeProductRequest.getDegree())) {
                throw new CrmebException("二手商品请填写新旧程度");
            }
            storeProduct.setDegree(storeProductRequest.getDegree());
        } else {
            //全新 商品默认推送状态0未推送
            storeProduct.setSelfPushStatus(0);
        }
        //计算价格
        calcPriceForAttrValues(storeProductRequest, storeProduct);

        //保存数据
        storeProduct.setIsEurope(ProductTypeEnum.INSIDE.getCode());
        if (storeProductRequest.getMerId() == 18) {
            BigDecimal renewal_price = priceUtil.getMoneyExchange(11);
            storeProduct.setExchangeRate(renewal_price);

        }
        boolean save = save(storeProduct);
        redisUtil.unlock(RedisUtil.PRODUCT_BARCODE_LOCK);
        if (null != storeProduct.getId()) {
            storeProductRequest.setId(storeProduct.getId());

            // 推荐图
            StoreProductMer merSave = new StoreProductMer();
            merSave.setIsSystemOut(0);
            merSave.setProductId(storeProduct.getId());
            merSave.setRecommendImg(storeProductRequest.getRecommendImg());
            merSave.setDeliveryData(storeProductRequest.getDeliveryData());
            merSave.setEarliestArrivalData(storeProductRequest.getEarliestArrivalData());
            merSave.setSlowestArrivalData(storeProductRequest.getSlowestArrivalData());
            merSave.setIsNotShow(storeProductRequest.getIsShow() ? "0" : "1");
            storeProductMerService.save(merSave);
        }
        if (storeProductRequest.getSpecType()) { // 多属性
            storeProductRequest.getAttr().forEach(e -> {
                e.setProductId(storeProduct.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
                e.setBarCode(storeProduct.getBarCode());
            });
            boolean attrAddResult = attrService.saveBatch(storeProductRequest.getAttr());
            if (!attrAddResult) {
                log.info("--------------- 新增多属性名失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性名失败");
            }
        } else { // 单属性
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            singleAttr.setBarCode(storeProduct.getBarCode());
            boolean attrAddResult = attrService.save(singleAttr);
            if (!attrAddResult) {
                log.info("--------------- 新增属性名失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性名失败");
            }
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            BigDecimal commissionL1 = BigDecimal.ZERO;
            BigDecimal commissionL2 = BigDecimal.ZERO;
            if (storeProductRequest.getAttrValue().size() > 0) {
                commissionL1 = null != storeProductRequest.getAttrValue().get(0).getBrokerage() ? storeProductRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                commissionL2 = null != storeProductRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
            }

            singleAttrValue.setProductId(storeProduct.getId())
                    .setStock(storeProduct.getStock())
                    .setSuk("默认")
                    .setAttrValue("{\"尺寸\":\"默认\"}")
                    .setSales(storeProduct.getSales())
                    .setPrice(storeProduct.getPrice())
                    .setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()))
                    .setCost(storeProduct.getCost())
                    .setSourceCost(storeProduct.getCost())
                    .setBarCode(storeProduct.getBarCode()).setSourceSkuId(storeProduct.getBarCode() + "-默认")
                    .setOtPrice(storeProduct.getOtPrice())
                    .setBrokerage(commissionL1).setBrokerageTwo(commissionL2);
            singleAttrValue.setBarCode(storeProduct.getBarCode());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            if (!saveOrUpdateResult) {
                log.info("--------------- 新增属性详情失败, 商品id: {} ---------------", storeProduct.getId());
                throw new CrmebException("新增属性详情失败");
            }
        }
        if (null != storeProductRequest.getAttrValue() && storeProductRequest.getAttrValue().size() > 0) {
            // 批量设置attrValues对象的商品id
            List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductRequest.getAttrValue();
            storeProductAttrValuesRequest.forEach(e -> {
                e.setProductId(storeProduct.getId());
            });
            List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
            for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                //设置sku字段
                if (null == attrValuesRequest.getAttrValue()) {
                    break;
                }
                List<String> skuList = new ArrayList<>();
                for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                    skuList.add(vo.getValue());
                    attrValuesRequest.setSuk(String.join(",", skuList));
                }
                attrValuesRequest.setSourceCost(attrValuesRequest.getCost());
                attrValuesRequest.setBarCode(storeProduct.getBarCode());
                attrValuesRequest.setSourceSkuId(attrValuesRequest.getBarCode() + "-" + attrValuesRequest.getSuk());
                StoreProductAttrValue spav = new StoreProductAttrValue();
                BeanUtils.copyProperties(attrValuesRequest, spav);
                spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                storeProductAttrValues.add(spav);
            }
            // 保存属性
            if (storeProductRequest.getSpecType() && storeProductAttrValues.size() <= 0) {
                throw new CrmebException("新增属性详情失败");
            }
            if (storeProductAttrValues.size() > 0) {
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0,*/ storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductRequest.getAttrValue())), DateUtil.getNowTime(), Constants.PRODUCT_TYPE_NORMAL, storeProductRequest.getBarCode());
                attrResult.setBarCode(storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult) {
                    throw new CrmebException("新增属性详情失败");
                }
            }
        }

        // 新增商品详情
        StoreProductDescription spd = StoreProductDescription.getDescriptionByProduct(storeProduct);
        spd.setProductId(storeProduct.getId());
        storeProductDescriptionService.save(spd);
        if (storeProductRequest.getDraftId() != null) {
            storeProductDraftService.removeById(storeProductRequest.getDraftId());
            storeProductAttrValueDraftService.remove(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                    .eq(StoreProductAttrValueDraft::getProductId, storeProductRequest.getId()));
        }

        // 处理优惠券关联信息
        shipProductCoupons(storeProductRequest, storeProduct);
        return save;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDrafts(StoreProductRequest storeProductRequest) {
        if (!redisUtil.lock(RedisUtil.PRODUCT_BARCODE_LOCK, "draftProduct", 1L)) {
            return false;
        }
        log.info("--------------- {}保存自建草稿箱商品: {} ---------------", systesmAdminService.getAdminId(), JSON.toJSONString(storeProductRequest));
        //设置barCode
        StoreBrand storeBrand = storeBrandService.getById(storeProductRequest.getBrandId());
        if (StringUtils.isBlank(storeProductRequest.getBarCode())) {
            storeProductRequest.setBarCode(getDraftProductBarCode(storeProductRequest.getMerId()));
        }
        StoreProductDraft storeProductDraft = new StoreProductDraft();
        BeanUtils.copyProperties(storeProductRequest, storeProductDraft, "degree");
        if (null != storeBrand) {
            storeProductDraft.setBrandName(storeBrand.getEnName());
        }
        storeProductDraft.setMerId(storeProductRequest.getMerId());
        storeProductDraft.setCateId(storeProductRequest.getCateId() + "");
        storeProductDraft.setSuppliersId(storeProductRequest.getSuppliersId() + "");
        //主图
        storeProductDraft.setImage(systemAttachmentService.clearPrefix(storeProductDraft.getImage()));
        //轮播图
        storeProductDraft.setSliderImage(systemAttachmentService.clearPrefix(storeProductDraft.getSliderImage()));
        // 获取 attrValue 字符串 解析后对应attrValue表中的数据
        if (BooleanUtils.isTrue(storeProductRequest.getSecondhand())) {
            storeProductDraft.setDegree(storeProductRequest.getDegree());
        }
        //保存数据
        storeProductDraft.setIsEurope(ProductTypeEnum.INSIDE.getCode());
        if (storeProductRequest.getMerId() == 18) {
            BigDecimal renewal_price = priceUtil.getMoneyExchange(11);
            storeProductDraft.setExchangeRate(renewal_price);
        }
        redisUtil.unlock(RedisUtil.PRODUCT_BARCODE_LOCK);
        if (storeProductRequest.getId() != null) {
            storeProductAttrValueDraftService.remove(Wrappers.<StoreProductAttrValueDraft>lambdaQuery()
                    .eq(StoreProductAttrValueDraft::getProductId, storeProductRequest.getId()));
        }
        if (storeProductRequest.getId() != null) {
            storeProductAttrValueDraftService.remove(Wrappers.<StoreProductAttrValueDraft>lambdaQuery().eq(StoreProductAttrValueDraft::getProductId, storeProductRequest.getId()));
        }
        //计算价格
        if (CollectionUtils.isEmpty(storeProductRequest.getAttrValue())) {
            storeProductDraft.setCost(BigDecimal.ZERO);
            storeProductDraft.setSourceCost(BigDecimal.ZERO);
            storeProductDraft.setPrice(BigDecimal.ZERO);
            storeProductDraft.setOtPrice(BigDecimal.ZERO);
            storeProductDraft.setStock(0);
            return storeProductDraftService.saveOrUpdate(storeProductDraft);
        } else {
            List<StoreProductAttrValueRequest> attrValues = storeProductRequest.getAttrValue();
            if (attrValues.stream().anyMatch(e -> e.getPrice() != null && e.getPrice().compareTo(BigDecimal.ZERO) < 0)) {
                throw new CrmebException("售价不能小于0");
            }
            if (attrValues.stream().anyMatch(e -> e.getCost() != null && e.getCost().compareTo(BigDecimal.ZERO) < 0)) {
                throw new CrmebException("成本价不能小于0");
            }
            if (attrValues.stream().anyMatch(e -> e.getOtPrice() != null && e.getOtPrice().compareTo(BigDecimal.ZERO) < 0)) {
                throw new CrmebException("原价不能小于0");
            }
            if (attrValues.stream().anyMatch(e -> e.getStock() != null && e.getStock() < 0)) {
                throw new CrmebException("库存不能小于0");
            }
            // 不要显示成本价，显示最低sku售价
            double costPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getCost() == null ? 0 : e.getCost().doubleValue()).min().orElse(0);
            //总库存
            int stock = storeProductRequest.getAttrValue().stream().mapToInt(e -> e.getStock() == null ? 0 : e.getStock()).sum();
            double sellPrice, otPrice;
            if (stock > 0) {
                sellPrice = storeProductRequest.getAttrValue().stream().filter(e -> e.getStock() > 0).mapToDouble(e -> e.getPrice() == null ? 0 : e.getPrice().doubleValue()).min().orElse(0);
                // 原价
                otPrice = storeProductRequest.getAttrValue().stream().filter(e -> e.getStock() > 0).mapToDouble(e -> e.getOtPrice() == null ? 0 : e.getOtPrice().doubleValue()).min().orElse(0);
            } else {
                sellPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice() == null ? 0 : e.getPrice().doubleValue()).min().orElse(0);
                otPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice() == null ? 0 : e.getOtPrice().doubleValue()).min().orElse(0);
            }
            storeProductDraft.setCost(BigDecimal.valueOf(costPrice));
            storeProductDraft.setSourceCost(BigDecimal.valueOf(costPrice));
            storeProductDraft.setPrice(BigDecimal.valueOf(sellPrice));
            storeProductDraft.setOtPrice(BigDecimal.valueOf(otPrice));
            storeProductDraft.setStock(stock);
            boolean save = storeProductDraftService.saveOrUpdate(storeProductDraft);
            if (!save) {
                return false;
            }
            //保存attrValue信息
            if (!storeProductRequest.getSpecType()) { // 单规格
                StoreProductAttrValueDraft singleAttrValue = new StoreProductAttrValueDraft();
                BigDecimal commissionL1 = BigDecimal.ZERO;
                BigDecimal commissionL2 = BigDecimal.ZERO;
                if (storeProductRequest.getAttrValue().size() > 0) {
                    commissionL1 = null != storeProductRequest.getAttrValue().get(0).getBrokerage() ? storeProductRequest.getAttrValue().get(0).getBrokerage() : BigDecimal.ZERO;
                    commissionL2 = null != storeProductRequest.getAttrValue().get(0).getBrokerageTwo() ? storeProductRequest.getAttrValue().get(0).getBrokerageTwo() : BigDecimal.ZERO;
                }
                singleAttrValue.setProductId(storeProductDraft.getId())
                        .setStock(storeProductDraft.getStock())
                        .setSuk("默认")
                        .setAttrValue("{\"尺寸\":\"默认\"}")
                        .setSales(storeProductDraft.getSales())
                        .setPrice(storeProductDraft.getPrice())
                        .setImage(systemAttachmentService.clearPrefix(storeProductDraft.getImage()))
                        .setCost(storeProductDraft.getCost())
                        .setSourceCost(storeProductDraft.getCost())
                        .setBarCode(storeProductDraft.getBarCode())
                        .setSourceSkuId(storeProductDraft.getBarCode() + "-默认")
                        .setOtPrice(storeProductDraft.getOtPrice())
                        .setBrokerage(commissionL1).setBrokerageTwo(commissionL2);
                singleAttrValue.setBarCode(storeProductDraft.getBarCode());
                boolean saveOrUpdateResult = storeProductAttrValueDraftService.save(singleAttrValue);
                if (!saveOrUpdateResult) {
                    log.info("--------------- 新增属性详情失败, 商品id: {} ---------------", storeProductDraft.getId());
                    throw new CrmebException("新增属性详情失败");
                }
                return saveOrUpdateResult;
            } else {
                // 批量设置attrValues对象的商品id
                attrValues.forEach(e -> {
                    e.setProductId(storeProductDraft.getId());
                });
                List<StoreProductAttrValueDraft> storeProductAttrValues = new ArrayList<>();
                for (StoreProductAttrValueRequest attrValuesRequest : attrValues) {
                    //设置sku字段
                    if (null == attrValuesRequest.getAttrValue()) {
                        break;
                    }
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                        attrValuesRequest.setSuk(String.join(",", skuList));
                    }
                    attrValuesRequest.setSourceCost(attrValuesRequest.getCost());
                    attrValuesRequest.setBarCode(storeProductDraft.getBarCode());
                    attrValuesRequest.setSourceSkuId(attrValuesRequest.getBarCode() + "-" + attrValuesRequest.getSuk());
                    StoreProductAttrValueDraft spav = new StoreProductAttrValueDraft();
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    spav.setImage(systemAttachmentService.clearPrefix(spav.getImage()));
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    storeProductAttrValues.add(spav);
                }
                return storeProductAttrValueDraftService.saveBatch(storeProductAttrValues);
            }
        }
    }


    /**
     * 更新产品
     *
     * @param storeProductRequest 更新产品request对象
     * @return 更新结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(StoreProductRequest storeProductRequest) {
        StoreProduct storeProduct = new StoreProduct();
        BeanUtils.copyProperties(storeProductRequest, storeProduct, "degree");
        storeProduct.setCreateTime(new Date());
        //二手判断
        if (BooleanUtils.isTrue(storeProductRequest.getSecondhand())) {
            if (StringUtils.isBlank(storeProductRequest.getDegree())) {
                throw new CrmebException("二手商品请填写新旧程度");
            }
            storeProduct.setDegree(storeProductRequest.getDegree());
        }

        //清空自建商品加价方式
        storeProductMerService.resetPrice(storeProductRequest.getId(), storeProductRequest.getMerId());
        //主图
        storeProduct.setImage(systemAttachmentService.clearPrefix(storeProduct.getImage()));

        //轮播图
        storeProduct.setSliderImage(systemAttachmentService.clearPrefix(storeProduct.getSliderImage()));

        //视频图
        storeProduct.setVideo(storeProductRequest.getVideoLink());

        StoreBrand storeBrand = storeBrandService.getById(storeProduct.getBrandId());
        if (null != storeBrand) {
            storeProduct.setBrandName(storeBrand.getEnName());
        }
        //        List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = getStoreProductAttrValueRequests(storeProductRequest);

        calcPriceForAttrValues(storeProductRequest, storeProduct);


        // 推荐图
        StoreProductMer storeProductMer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                .eq(StoreProductMer::getProductId, storeProduct.getId())
                .last("LIMIT 1")
        );
        if (null != storeProductMer) {
            storeProductMer.setRecommendImg(storeProductRequest.getRecommendImg());
            storeProductMer.setDeliveryData(storeProductRequest.getDeliveryData());
            storeProductMer.setEarliestArrivalData(storeProductRequest.getEarliestArrivalData());
            storeProductMer.setSlowestArrivalData(storeProductRequest.getSlowestArrivalData());
            storeProductMer.setIsNotShow(storeProduct.getIsShow() ? "0" : "1");
            storeProductMerService.updateById(storeProductMer);
        } else {
            storeProductMer = new StoreProductMer();
            storeProductMer.setIsSystemOut(0);
            storeProductMer.setProductId(storeProduct.getId());
            storeProductMer.setRecommendImg(storeProductRequest.getRecommendImg());
            storeProductMer.setDeliveryData(storeProductRequest.getDeliveryData());
            storeProductMer.setEarliestArrivalData(storeProductRequest.getEarliestArrivalData());
            storeProductMer.setSlowestArrivalData(storeProductRequest.getSlowestArrivalData());
            storeProductMer.setIsNotShow(storeProduct.getIsShow() ? "0" : "1");
            storeProductMerService.save(storeProductMer);
        }
        //storeProduct.setIsShow(!Objects.equals(storeProductMer.getIsNotShow(), "1"));
        int saveCount = storeProductDAO.updateById(storeProduct);
        StoreProduct product = storeProductDAO.selectOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, storeProduct.getId())
                .select(StoreProduct::getBarCode));
        // 对attr表做全量更新，删除原有数据保存现有数据
        attrService.removeByProductId(storeProduct.getId());
        // 查出所有的sku属性,用suk找到相同的属性,做更新
        //        storeProductAttrValueService.removeByProductId(storeProduct.getId());
        List<StoreProductAttrValue> attrValuelist = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, storeProduct.getId()));
        Map<String, StoreProductAttrValue> attrValueMap = attrValuelist == null ? MapUtil.newHashMap() : attrValuelist.stream().collect(Collectors.toMap(StoreProductAttrValue::getSuk, Function.identity(), (v1, v2) -> v2));
        if (CollectionUtils.isNotEmpty(storeProductRequest.getAttrValue())) {
            storeProductRequest.getAttrValue().forEach(attrValueRequest -> {
                if (null != attrValueRequest.getAttrValue()) {
                    List<String> skuList = new ArrayList<>();
                    for (Map.Entry<String, String> vo : attrValueRequest.getAttrValue().entrySet()) {
                        skuList.add(vo.getValue());
                    }
                    attrValueRequest.setSuk(String.join(",", skuList));
//                    attrValueRequest.setId(attrValueMap.containsKey(attrValueRequest.getSuk()) ? attrValueMap.get(attrValueRequest.getSuk()).getId() : null);
                }
            });
        }

        if (storeProductRequest.getSpecType()) { // todo 确认单属性商品的attr参数
            storeProductRequest.getAttr().forEach(e -> {
                e.setProductId(storeProductRequest.getId());
                e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
            });
            attrService.saveBatch(storeProductRequest.getAttr());
            if (CollectionUtils.isNotEmpty(storeProductRequest.getAttrValue())) {
                storeProductAttrValueService.removeByProductId(storeProductRequest.getId());
                List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductRequest.getAttrValue();
                // 批量设置attrValues对象的商品id
                storeProductAttrValuesRequest.forEach(e -> e.setProductId(storeProductRequest.getId()));
                List<StoreProductAttrValue> storeProductAttrValues = new ArrayList<>();
                for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
                    StoreProductAttrValue spav = new StoreProductAttrValue();
                    attrValuesRequest.setSourceCost(attrValuesRequest.getCost());
                    attrValuesRequest.setBarCode(product.getBarCode());
                    attrValuesRequest.setSourceSkuId(attrValuesRequest.getBarCode() + "-" + attrValuesRequest.getSuk());
                    BeanUtils.copyProperties(attrValuesRequest, spav);
                    // 设置id
                    //设置sku字段
                    //                    if(null != attrValuesRequest.getAttrValue()){
                    //                        List<String> skuList = new ArrayList<>();
                    //                        for(Map.Entry<String,String> vo: attrValuesRequest.getAttrValue().entrySet()){
                    //                            skuList.add(vo.getValue());
                    //                        }
                    //                        spav.setSuk(String.join(",",skuList));
                    //                    }
                    //                    HashMap<String, Object> attrValues = setAttrValueByRequest(storeProductRequest);
                    spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
                    //                    spav.setAttrValue(JSON.toJSONString(attrValues));
                    storeProductAttrValues.add(spav);
                }
                boolean saveOrUpdateResult = storeProductAttrValueService.saveBatch(storeProductAttrValues);
                // attrResult整存整取，不做更新
                storeProductAttrResultService.deleteByProductId(storeProduct.getId());
                StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductRequest.getAttrValue())), DateUtil.getNowTime(), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
                storeProductAttrResultService.save(attrResult);
                if (!saveOrUpdateResult)
                    throw new CrmebException("编辑属性详情失败");

            }
        } else {
            StoreProductAttr singleAttr = new StoreProductAttr();
            singleAttr.setProductId(storeProduct.getId()).setAttrName("规格").setAttrValues("默认").setType(0);
            boolean attrAddResult = attrService.save(singleAttr);
            if (!attrAddResult)
                throw new CrmebException("新增属性名失败");
            StoreProductAttrValue singleAttrValue = new StoreProductAttrValue();
            if (storeProductRequest.getAttrValue().size() == 0)
                throw new CrmebException("attrValue不能为空");
            StoreProductAttrValueRequest attrValueRequest = storeProductRequest.getAttrValue().get(0);
            BeanUtils.copyProperties(attrValueRequest, singleAttrValue);
            singleAttrValue.setProductId(storeProduct.getId());
            singleAttrValue.setSuk("默认");
            singleAttrValue.setImage(systemAttachmentService.clearPrefix(singleAttrValue.getImage()));
            storeProductAttrValueService.removeByProductId(storeProductRequest.getId());
            boolean saveOrUpdateResult = storeProductAttrValueService.save(singleAttrValue);
            if (!saveOrUpdateResult)
                throw new CrmebException("新增属性详情失败");
        }

        // 处理分类辅助表
        if (null != storeProductRequest.getCateIds()) {
            for (int i = 0; i < storeProductRequest.getCateIds().size(); i++) {
                Integer cateid = storeProductRequest.getCateIds().get(i);
                StoreProductCate storeProductCate = new StoreProductCate(storeProduct.getId(), cateid, DateUtil.getNowTime());
                LambdaUpdateWrapper<StoreProductCate> luw = new LambdaUpdateWrapper<>();
                luw.set(StoreProductCate::getProductId, storeProductCate.getProductId());
                luw.set(StoreProductCate::getCateId, storeProductCate.getCateId());
                luw.set(StoreProductCate::getAddTime, storeProductCate.getAddTime());
                storeProductCateService.update(luw);
                //                if(!updateResult) throw new CrmebException("编辑产品分类辅助失败");
            }
        }

        /****** Description表保存 ******/
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                .eq(StoreProductDescription::getProductId, storeProduct.getId())
                .last("LIMIT 1")
        );
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByProduct(storeProduct);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(storeProduct.getId());
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

        // 处理优惠券关联信息
        shipProductCoupons(storeProductRequest, storeProduct);
        return saveCount > 0;
    }

    /**
     * 商品详情
     *
     * @param id 商品id
     * @return 详情数据
     */
    @Override
    public StoreProductNormResponse getSupplierByProductId(int id, Integer merId) {
        StoreProductNormResponse response = new StoreProductNormResponse();
        StoreProduct product = storeProductDAO.selectById(id);
        // 暂写死固定自营小程序私域图权限
        if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
            product.setMt(null);
            product.setSp2(null);
        }
        Integer normId = product.getNormId();
        // 是否多供应商详情展示
        SystemConfig systemConfig = systemConfigService.getMerchantCustomConfig(merId, Constants.CONFIG_PRODUCT_DETAIL);
        Boolean productDetails = null != systemConfig && "0".equals(systemConfig.getValue()) ? true : false;
        if (null != normId && productDetails) {
            response.setProductNorm(storeProductNormDAO.selectById(normId));
            response.setProducts(listByNormId(normId, merId));
            String description = storeProductNormDescriptionService.getProductNormDesc(normId);
            if (Objects.nonNull(response.getProductNorm()) && StringUtils.isNotBlank(description)) {
                response.getProductNorm().setStoreInfo(description);
            }
        } else {
            StoreProductResponse storeProductResponse = getByProductId(id, merId, false, false, null, false);
            List<StoreProductResponse> storeProductResponses = Arrays.asList(storeProductResponse);
            response.setProducts(storeProductResponses);

            // 使用自建商品属性赋值到标准商品上
            if (CollectionUtils.isNotEmpty(storeProductResponses)) {
                StoreProductNorm norm = new StoreProductNorm();
                BeanUtils.copyProperties(storeProductResponses.get(0), norm);
                response.setProductNorm(norm);
            }
        }

        return response;
    }

    /**
     * 商品详情
     *
     * @param id 商品id
     * @return 详情数据
     */
    private List<StoreProductResponse> listByNormId(int id, Integer merId) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        productUtil.getChannelMerchantAuth(lambdaQueryWrapper, merId);
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.eq(StoreProduct::getNormId, id);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, 1);
        lambdaQueryWrapper.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE.getCode());
        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (ObjectUtils.isNotEmpty(channelMerchant)) {
            List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            if (null != brandIdsList && brandIdsList.size() > 0) {
                lambdaQueryWrapper.in(StoreProduct::getBrandId, brandIdsList);
            }
            if (null != suppliersIdList && suppliersIdList.size() > 0) {
                lambdaQueryWrapper.in(StoreProduct::getSuppliersId, suppliersIdList);
            }
            if (null != tempIdList && tempIdList.size() > 0) {
                lambdaQueryWrapper.in(StoreProduct::getTempId, tempIdList);
            }
        }
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return null;
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
        // 商品desc
//        Map<Integer, String> productDescMap = storeProductDescriptionService.getProductDescMap(storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList()));

        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        //等级会员
        List<ChannelMemberLevel> memberLevelList = channelMemberLevelService.getMemberLevelList(1, merId, Arrays.asList(2, 3));
        for (StoreProduct storeProduct : storeProducts) {
            // 加价计算规则
            Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(Collections.singletonList(storeProduct), merId, AreaTypeEnum.CN.getType());
            //计算等级会员价格
            priceUtil.calcMemberLevelProductPrice(Collections.singletonList(storeProduct), channelMerchant, memberLevelList);
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(storeProduct, storeProductResponse);
            // 暂写死固定自营小程序私域图权限
            if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
                storeProductResponse.setMt(null);
                storeProductResponse.setSp2(null);
            }
            //加价计算方式
            String calculation = priceUtil.getCalculation(storeProduct.getMarkupType(), storeProduct.getPriceChange(), null);
            storeProductResponse.setCalculation(calculation);
            storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
            //发货时间
            storeProductResponse.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProduct.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
            String receivingTime = productUtil.getReceivingTime(storeProductResponse.getStockArea(), storeProductResponse.getIsEurope(), storeProduct.getMerId(), storeProduct.getId());
            storeProductResponse.setReceivingTime(receivingTime);
            // 推荐图
//            StoreProductMer storeProductMer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
//                    .eq(StoreProductMer::getProductId, storeProduct.getId())
//                    .last("LIMIT 1")
//                    );
//            if(null != storeProductMer) {
//                storeProductResponse.setRecommendImg(storeProductMer.getRecommendImg());
//            }
            // 设置sku属性
            storeProductResponse.setAttr(attrService.getByProductId(storeProduct.getId()));
            List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getListByProductId(storeProduct.getId());

            storeProductStockService.showStockBatch(storeProductAttrValues);

            if (CollectionUtils.isEmpty(storeProductAttrValues)) {
                continue;
            }

            // 根据attrValue生成前端所需的数据
            List<HashMap<String, Object>> attrValues = new ArrayList<>();
            Map<String, StoreProductAttrValue> valMap = new HashMap<>();
            // 加价计算规则
            priceUtil.calcProductValuePrice(storeProductAttrValues, merId, storeProduct, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
            //计算等级会员价格
            priceUtil.calcMemberLevelValuePrice(storeProductAttrValues, channelMerchant, memberLevelList);
            for (StoreProductAttrValue spav : storeProductAttrValues) {
                valMap.put(spav.getAttrValue(), spav);
            }
            if (storeProduct.getSpecType()) {
                // 后端多属性用于编辑
                StoreProductAttrResult attrResult = storeProductAttrResultService.getByProductId(storeProduct.getId());
                //PC 端生成skuAttrInfo
                List<StoreProductAttrValueRequest> storeProductAttrValueRequests = com.alibaba.fastjson.JSONObject.parseArray(attrResult.getResult(), StoreProductAttrValueRequest.class);
                if (null != storeProductAttrValueRequests) {
                    for (int i = 0; i < storeProductAttrValueRequests.size(); i++) {
                        StoreProductAttrValueRequest storeProductAttrValueRequest = storeProductAttrValueRequests.get(i);
                        StoreProductAttrValue attrVal = valMap.get(JSON.toJSONString(storeProductAttrValueRequest.getAttrValue()));
                        if (null == attrVal) {
                            continue;
                        }
                        HashMap<String, Object> attrValue = new HashMap<>();
                        attrValue.put("image", storeProductAttrValueRequest.getImage());
                        attrValue.put("cost", attrVal.getCost().setScale(2, BigDecimal.ROUND_UP));
                        attrValue.put("taxAndSecondPrice", attrVal.getTaxAndSecondPrice().setScale(2, BigDecimal.ROUND_UP));
                        attrValue.put("price", attrVal.getPrice().setScale(2, BigDecimal.ROUND_UP));
                        attrValue.put("otPrice", storeProductAttrValueRequest.getOtPrice());
                        // 不能显示result里的库存
                        attrValue.put("stock", attrVal.getStock());
                        attrValue.put("barCode", storeProductAttrValueRequest.getBarCode());
                        attrValue.put("weight", storeProductAttrValueRequest.getWeight());
                        attrValue.put("volume", storeProductAttrValueRequest.getVolume());
                        attrValue.put("suk", attrVal.getSuk());
                        attrValue.put("attrValue", JSON.parse(attrVal.getAttrValue()));
                        attrValue.put("brokerage", storeProductAttrValueRequest.getBrokerage());
                        attrValue.put("brokerage_two", storeProductAttrValueRequest.getBrokerageTwo());
                        attrValue.put("sourceSkuId", storeProductAttrValueRequest.getSourceSkuId());
                        Iterator<Map.Entry<String, String>> iterator = storeProductAttrValueRequest.getAttrValue().entrySet().iterator();
                        int j = 0;
                        while (iterator.hasNext()) {
                            Map.Entry<String, String> entry = iterator.next();
                            attrValue.put("value" + j, entry.getValue());
                            j += 1;
                        }
                        attrValues.add(attrValue);
                    }
                }
            }

            // H5 端用于生成skuList
            List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
            for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
                StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(storeProductAttrValue, atr);
                atr.setPrice(atr.getPrice().setScale(2, RoundingMode.HALF_UP));
                //tax
                atr.setTaxAndSecondPrice(atr.getTaxAndSecondPrice().setScale(2, RoundingMode.HALF_UP));
                atr.setCost(atr.getCost().setScale(2, RoundingMode.HALF_UP));
                atr.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
                atr.setReceivingTime(productUtil.getReceivingTime(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
                sPAVResponses.add(atr);
            }

            storeProductResponse.setAttrValues(attrValues);
            storeProductResponse.setAttrValue(sPAVResponses);

            storeProductResponses.add(storeProductResponse);
        }

        return storeProductResponses;
    }

    /**
     * 商品详情
     *
     * @param id     商品id
     * @param flag   是否计算会员价格
     * @param isUser 是否前端用户
     * @return 详情数据
     */
    @Override
    public StoreProductResponse getByProductId(int id, Integer merId, boolean flag, boolean isUser, String groupId, boolean isCart) {
        StoreProduct storeProduct = storeProductDAO.selectById(id);
        if (null == storeProduct) {
            throw new CrmebException("未找到对应商品信息");
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProduct);
        // todo 只要查询了这个分表就必须重新绑定线程
        MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
        MybatisPlusConfig.productValueNameMp.set(TableNameUtil.getProductValueMerName(merId));
        StoreProductMer mer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                .eq(StoreProductMer::getProductId, storeProduct.getId())
        );
        //等级会员
        List<Integer> levelList = new ArrayList<>();
        if (isUser) {
            User user = userService.getInfo();
            levelList.add(user != null ? user.getLevel() : 0);
        } else {
            levelList.addAll(Arrays.asList(2, 3));
        }
        List<ChannelMemberLevel> memberLevelList = channelMemberLevelService.getMemberLevelList(1, merId, levelList);
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        // 加价计算规则
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(Collections.singletonList(storeProduct), merId, AreaTypeEnum.CN.getType());
        priceUtil.calcMemberLevelProductPrice(Collections.singletonList(storeProduct), channelMerchant, memberLevelList);
        //折扣信息
        BigDecimal discountRatio = null;
        List<Integer> memberProductIdList = new ArrayList<>();
        if (flag) {
            //计算会员折扣价格
            Map<BigDecimal, List<Integer>> memberDiscountMap = priceUtil.calcMemberDiscountPrice(Collections.singletonList(storeProduct), merId, false);
            if (CollectionUtils.isNotEmpty(memberDiscountMap)) {
                for (Map.Entry<BigDecimal, List<Integer>> entry : memberDiscountMap.entrySet()) {
                    discountRatio = entry.getKey();
                    memberProductIdList = entry.getValue();
                }
            }
        }
        StoreProductResponse storeProductResponse = new StoreProductResponse();
        BeanUtils.copyProperties(storeProduct, storeProductResponse);
        // 暂写死固定自营小程序私域图权限
        if (18 != merId && 30 != merId/* && 45 != merId && 47 != merId*/) {
            storeProductResponse.setMt(null);
            storeProductResponse.setSp2(null);
        }

        //加价计算方式
        String calculation = priceUtil.getCalculation(storeProduct.getMarkupType(), storeProduct.getPriceChange(), null);
        storeProductResponse.setCalculation(calculation);
        storeProductResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
        if (Objects.equals(storeProduct.getIsEurope(), 1)) {
            if (!Objects.isNull(mer)) {
                storeProductResponse.setDeliveryData(mer.getDeliveryData());
                storeProductResponse.setEarliestArrivalData(mer.getEarliestArrivalData());
                storeProductResponse.setSlowestArrivalData(mer.getSlowestArrivalData());
            }
        }
        //发货时间
        storeProductResponse.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProduct.getTempId(), storeProduct.getIsEurope(), merId, storeProduct.getId()));
        //收货时间
        String receivingTime = productUtil.getReceivingTime(storeProductResponse.getStockArea(), storeProductResponse.getIsEurope(), storeProduct.getMerId(), storeProduct.getId());
        storeProductResponse.setReceivingTime(receivingTime);
        // 推荐图
//        StoreProductMer storeProductMer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
//                .eq(StoreProductMer::getMerId, merId)
//                .eq(StoreProductMer::getProductId, storeProduct.getId())
//                .last("LIMIT 1")
//                );
        //2023.6.7添加自建和云仓的区别
        if (storeProduct.getIsEurope() == 1) //自建
        {
            storeProductResponse.setShippingTempId(storeProduct.getShippingTempId());
        } else {
            if (null != mer) {
                storeProductResponse.setRecommendImg(mer.getRecommendImg());
                if ("1".equals(mer.getIsNotShow())) {
                    storeProductResponse.setIsShow(false);
                }
                storeProductResponse.setShippingTempId(mer.getShippingTempId());
            }
        }

        // 设置sku属性
        storeProductResponse.setAttr(attrService.getByProductId(storeProduct.getId()));
        List<StoreProductAttrValue> storeProductAttrValues = storeProductAttrValueService.getListByProductId(storeProduct.getId());

        // 只对后台用户处理库存量，前端用户只显示剩余可用的库存
        if(!flag) {
            storeProductStockService.showStockBatch(storeProductAttrValues);

        }else {
            // 计算库存和价格
            if(groupId != null && !"0".equals(groupId)) {
                storeProductStockService.calcStockAndPrice(groupId, null, storeProductAttrValues);
            }else{
                storeProductAttrValues.stream().forEach(i -> {
                    if (null != i.getGroupStock()) {
                        i.setGroupStock(null);
                    }
                });
            }
        }

        if (CollectionUtils.isEmpty(storeProductAttrValues)) {
            return storeProductResponse;
        }

        // 根据attrValue生成前端所需的数据
        List<HashMap<String, Object>> attrValues = new ArrayList<>();
        Map<String, StoreProductAttrValue> valMap = new HashMap<>();
        // 加价计算规则(sku维度)
        priceUtil.calcProductValuePrice(storeProductAttrValues, merId, storeProduct, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
        priceUtil.calcMemberLevelValuePrice(storeProductAttrValues, channelMerchant, memberLevelList);
        if (flag) {
            if (discountRatio != null && memberProductIdList.contains(storeProduct.getId())) {
                priceUtil.calcValueMemberDiscountPrice(storeProductAttrValues, discountRatio, channelMerchant.getAppletType());
            }
        }
        for (StoreProductAttrValue spav : storeProductAttrValues) {
            valMap.put(spav.getAttrValue(), spav);
        }
        if (storeProduct.getSpecType()) {
            // 后端多属性用于编辑
            StoreProductAttrResult attrResult = storeProductAttrResultService.getByProductId(storeProduct.getId());
            //PC 端生成skuAttrInfo
            List<StoreProductAttrValueRequest> storeProductAttrValueRequests = com.alibaba.fastjson.JSONObject.parseArray(attrResult.getResult(), StoreProductAttrValueRequest.class);
            if (null != storeProductAttrValueRequests) {
                for (int i = 0; i < storeProductAttrValueRequests.size(); i++) {
                    StoreProductAttrValueRequest storeProductAttrValueRequest = storeProductAttrValueRequests.get(i);
                    StoreProductAttrValue attrVal = valMap.get(JSON.toJSONString(storeProductAttrValueRequest.getAttrValue()));
                    if (null == attrVal) {
                        continue;
                    }
                    HashMap<String, Object> attrValue = new HashMap<>();
                    attrValue.put("image", storeProductAttrValueRequest.getImage());
                    attrValue.put("cost", attrVal.getCost().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("taxAndSecondPrice", attrVal.getTaxAndSecondPrice().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("price", attrVal.getPrice().setScale(2, BigDecimal.ROUND_UP));
                    attrValue.put("otPrice", storeProductAttrValueRequest.getOtPrice());
                    // 不能显示result里的库存
                    attrValue.put("stock", attrVal.getStock());
//                    if(null != attrVal.getGroupStock() && attrVal.getGroupStock() > 0){
//                        attrValue.put("groupStock", attrVal.getGroupStock());
//                    }else {
//                        attrValue.put("groupStock", 0);
//                    }
                    attrValue.put("barCode", storeProductAttrValueRequest.getBarCode());
                    attrValue.put("weight", storeProductAttrValueRequest.getWeight());
                    //2023.6.7特殊处理
                    StoreProductValueMer productValueMer = storeProductValueMerService.getOne(Wrappers.lambdaQuery(StoreProductValueMer.class)
                            .eq(StoreProductValueMer::getProductId, storeProductAttrValueRequest.getProductId())
                            .eq(StoreProductValueMer::getSourceSkuId, storeProductAttrValueRequest.getSourceSkuId()));

                    if (null != productValueMer) {
                        attrValue.put("volume", productValueMer.getVolume());
                    } else {
                        attrValue.put("volume", storeProductAttrValueRequest.getVolume());
                    }

                    attrValue.put("suk", attrVal.getSuk());
                    attrValue.put("attrValue", JSON.parse(attrVal.getAttrValue()));
                    attrValue.put("brokerage", storeProductAttrValueRequest.getBrokerage());
                    attrValue.put("brokerage_two", storeProductAttrValueRequest.getBrokerageTwo());
                    attrValue.put("sourceSkuId", storeProductAttrValueRequest.getSourceSkuId());
                    Iterator<Map.Entry<String, String>> iterator = storeProductAttrValueRequest.getAttrValue().entrySet().iterator();
                    int j = 0;
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> entry = iterator.next();
                        attrValue.put("value" + j, entry.getValue());
                        j += 1;
                    }
                    attrValues.add(attrValue);
                }
            }
        }

        // H5 端用于生成skuList
        List<StoreProductAttrValueResponse> sPAVResponses = new ArrayList<>();
        for (StoreProductAttrValue storeProductAttrValue : storeProductAttrValues) {
            StoreProductAttrValueResponse atr = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(storeProductAttrValue, atr);
            atr.setPrice(atr.getPrice().setScale(2, RoundingMode.HALF_UP));
            //tax
            atr.setTaxAndSecondPrice(atr.getTaxAndSecondPrice().setScale(2, RoundingMode.HALF_UP));
            atr.setCost(atr.getCost().setScale(2, RoundingMode.HALF_UP));
            atr.setDeliveryTime(productUtil.getDeliveryTimeByTempId(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));
            atr.setReceivingTime(productUtil.getReceivingTime(storeProductAttrValue.getTempId(), storeProduct.getIsEurope(), storeProduct.getMerId(), storeProduct.getId()));

            StoreProductValueMer productValueMer = storeProductValueMerService.getOne(Wrappers.lambdaQuery(StoreProductValueMer.class)
                    .eq(StoreProductValueMer::getProductId, storeProductAttrValue.getProductId())
                    .eq(StoreProductValueMer::getSourceSkuId, storeProductAttrValue.getSourceSkuId())
                    .orderByDesc(StoreProductValueMer::getId)
                    .last("LIMIT 1")
            );

            if (null != productValueMer) {
                atr.setVolume(productValueMer.getVolume());
            } else {
                atr.setVolume(storeProductAttrValue.getVolume());
            }

            sPAVResponses.add(atr);
        }
        storeProductResponse.setAttrValues(attrValues);
        storeProductResponse.setAttrValue(sPAVResponses);

        return storeProductResponse;
    }

    /**
     * 商品详情
     *
     * @param id     商品id
     * @return 详情数据
     */
    @Override
    public StoreProductMer getProductMerById(int id, Integer merId) {
        StoreProduct storeProduct = storeProductDAO.selectById(id);
        if (null == storeProduct) {
            throw new CrmebException("未找到对应商品信息");
        }
        // todo 只要查询了这个分表就必须重新绑定线程
        MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
        MybatisPlusConfig.productValueNameMp.set(TableNameUtil.getProductValueMerName(merId));
        StoreProductMer mer = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
                .eq(StoreProductMer::getProductId, storeProduct.getId())
        );

        return mer;
    }

    /**
     * 商品列表 - 查询条件
     *
     * @param request
     * @param lambdaQueryWrapper
     */
    private void queryCondition(IndexStoreProductSearchRequest request, LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper) {
        // 查询商户信息(redis获取)
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(request.getMerId());
        // 解析权限内json数据
        List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        // 品牌过滤
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(brandIdsList), StoreProduct::getBrandId, brandIdsList);

        // 专区id
        if (request.getZoneId() != null && request.getZoneId() != 0) {
            Integer zoneId = request.getZoneId();
            List<StoreZoneProduct> storeZoneProductList = storeZoneProductService.list(Wrappers.lambdaQuery(StoreZoneProduct.class)
                    .eq(StoreZoneProduct::getZoneId, zoneId)
            );
            List<Integer> zoneProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());

            if(CollectionUtils.isNotEmpty(zoneProductIdList)){
                if(CollectionUtils.isNotEmpty(request.getProductIdList())){
                    // 使用Set来去重
                    Set<Integer> set = new HashSet<>();

                    // 添加两个列表的数据到Set中
                    set.addAll(zoneProductIdList);
                    set.addAll(request.getProductIdList());

                    // 转换回List并返回
                    request.setProductIdList(new ArrayList<>(set));
                }else {
                    request.setProductIdList(zoneProductIdList) ;
                }
            }

        }
        // 商品id过滤
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(request.getProductIdList()), StoreProduct::getId, request.getProductIdList());

        // 发货地过滤
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(tempIdList), StoreProduct::getTempId, tempIdList);
        // 商户对应自建供应商
        Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
        lambdaQueryWrapper.and(
                e -> e.eq(StoreProduct::getSuppliersId, supplier != null ? supplier.getId().toString() : 0)
                        .or(
                                i -> i.in(CollectionUtils.isNotEmpty(suppliersIdList), StoreProduct::getSuppliersId, suppliersIdList).and(
                                        a -> a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                                .or(b -> b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).isNotNull(StoreProduct::getConvertIsEurope))
                                )
                        )
        );
//    	lambdaQueryWrapper.and(a->a.and(e->e.in(CollectionUtils.isNotEmpty(suppliersIdList),StoreProduct::getSuppliersId, suppliersIdList).ne(StoreProduct::getIsEurope,1))
//    			.or(null != supplier,e->e.eq(StoreProduct::getIsEurope,1).eq(StoreProduct::getSuppliersId,supplier.getId())));
//        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
//            Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
//            if (null != supplier) {
//                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
//                suppliersIdList.add(supplier.getId().toString());
//            }
//            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, suppliersIdList);
//        }

        //必要条件
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        // 查询商户上架商品
        lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(request.getMerId()) + " WHERE is_not_show = 0");
        // 搜索关键词
        String keywords = request.getKeywords();
        if (StringUtils.isNotBlank(keywords)) {
            lambdaQueryWrapper.and(wrap -> wrap
                    .apply("LOCATE({0},keyword)>0 OR LOCATE({0}, store_name)>0 OR LOCATE({0}, brand_name)>0", keywords));
        }
        // 意大利轮播图-商品列表(应该失效了)
        if (BooleanUtil.isTrue(request.getIsEurope())) {
            lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.EUROPE.getCode());
        }
        // 发货地
        if (StringUtils.isNotBlank(request.getStockArea())) {
            List<Integer> stockAreaList = new ArrayList<>();
            String[] strAreas = request.getStockArea().split(",");
            for (String s : strAreas) {
                stockAreaList.add(Integer.parseInt(s));
            }
            if (stockAreaList.size() == 1) {
                lambdaQueryWrapper.eq(StoreProduct::getTempId, stockAreaList.get(0));
            } else {
                lambdaQueryWrapper.in(StoreProduct::getTempId, stockAreaList);
            }
        }
        // 图搜BarCode
        if (CollectionUtils.isNotEmpty(request.getBarCodeArr())) {
            lambdaQueryWrapper.in(StoreProduct::getBarCode, request.getBarCodeArr());
        }
        // 新增条件最低高价格 最大小库存
        if (request.getMinPrice() != null || request.getMaxPrice() != null) {
            MarkupRateRequest rateRequest = new MarkupRateRequest();
            rateRequest.setMerId(request.getMerId());
            rateRequest.setType(MarkupRateTypeEnum.PLAT_平台加价率.getType());
            BigDecimal platRatio = markupRateService.selectMerchantRatio(rateRequest);
            rateRequest.setType(MarkupRateTypeEnum.MERCHANT_商户加价率.getType());
            BigDecimal merRatio = markupRateService.selectMerchantRatio(rateRequest);
            if (request.getMinPrice() != null && request.getMaxPrice() == null) {
                lambdaQueryWrapper.ge(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMinPrice(), platRatio, merRatio));
            } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.le(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMaxPrice(), platRatio, merRatio));
            } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.between(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMinPrice(), platRatio, merRatio), UnitConvertUtil.getRequestPrice(request.getMaxPrice(), platRatio, merRatio));
            }
        }
        // 新品
        if (request.getIsNew() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getIsNew, request.getIsNew());
        }
        // 上架
        if (request.getIsShow() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getIsShow, request.getIsShow());
        }
        // 品牌或品牌列表
        if (request.getBrandId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if (StringUtils.isNotBlank(request.getBrandIds())) {
            String[] brds = request.getBrandIds().split(",");
            lambdaQueryWrapper.in(StoreProduct::getBrandId, Arrays.asList(brds));
        }
        // 供应商
        if (StringUtils.isNotBlank(request.getSuppliersIds())) {
            String[] suppliersIds = request.getSuppliersIds().split(",");
            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, Arrays.asList(suppliersIds));
        }
        // 类目
        if (CollectionUtils.isNotEmpty(request.getCateId())) {
            lambdaQueryWrapper.in(StoreProduct::getCateId, request.getCateId());
        }
        // 过滤禁用或失效分类
        if (Objects.nonNull(request.getMerId())) {
            List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);
        }
        // 精选/小编推荐
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(request.getMerId()) + " WHERE is_best = 1 AND is_not_show = 0");
        }
        // 折扣价查询条件
        if (request.getMinDiscount() != null && request.getMaxDiscount() == null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 >= {0} ", request.getMinDiscount());
        } else if (request.getMinDiscount() == null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 <= {0} ", request.getMaxDiscount());
        } else if (request.getMinDiscount() != null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 BETWEEN  {0} and {1} ", request.getMinDiscount(), request.getMaxDiscount());
        }
        // 销量排序
        if (StringUtils.isNotBlank(request.getSalesOrder())) {
            if (request.getSalesOrder().equals(Constants.SORT_DESC)) {
                lambdaQueryWrapper.orderByDesc(StoreProduct::getSales);
            } else {
                lambdaQueryWrapper.orderByAsc(StoreProduct::getSales);
            }
        }
        // 价格排序
        if (StringUtils.isNotBlank(request.getPriceOrder())) {
            if (request.getPriceOrder().equals(Constants.SORT_DESC)) {
                lambdaQueryWrapper.orderByDesc(StoreProduct::getPrice);
            } else {
                lambdaQueryWrapper.orderByAsc(StoreProduct::getPrice);
            }
        }
        // 折扣排序 放在最后
        if (StringUtils.isNotBlank(request.getDiscountSort())) {
            if (StringUtils.isBlank(request.getPriceOrder()) && StringUtils.isBlank(request.getSalesOrder())) {
                lambdaQueryWrapper.last(" order by round(price / (ot_price * exchange_rate),2) * 10 " + request.getDiscountSort());
            } else {
                lambdaQueryWrapper.last(",round(price / (ot_price * exchange_rate),2) * 10 " + request.getDiscountSort());
            }
        } else {
            // 推送时间排序
            lambdaQueryWrapper.orderByDesc(StoreProduct::getLastPushTime);
        }
        // 用户优惠券跳转
        if (null != request.getUserCouponId()) {
            StoreCouponUser storeCouponUser = frontCouponUserService.getById(request.getUserCouponId());
            if (null != storeCouponUser) {
                if (CouponUseTypeEnum.GOODS.getCode().equals(storeCouponUser.getUseType())) {
                    List<Integer> productIds = frontCouponUserService.listCouponUserProductId(storeCouponUser.getCouponId());
                    lambdaQueryWrapper.in(StoreProduct::getId, productIds);
                } else if (CouponUseTypeEnum.CATE.getCode().equals(storeCouponUser.getUseType()) && StringUtils.isNotBlank(storeCouponUser.getPrimaryKey())) {
                    CouponProductRangeDTO couponProductRangeDTO = com.alibaba.fastjson.JSONObject.parseObject(storeCouponUser.getPrimaryKey(), CouponProductRangeDTO.class);
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getCateIds()), StoreProduct::getCateId, couponProductRangeDTO.getCateIds());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getTempIds()), StoreProduct::getTempId, couponProductRangeDTO.getTempIds());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getSeasons()), StoreProduct::getSeasonCode, couponProductRangeDTO.getSeasons());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getBrandids()), StoreProduct::getBrandId, couponProductRangeDTO.getBrandids());
                }
            }
        }
        // 季节
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(request.getSeason()), StoreProduct::getSeasonCode, request.getSeason());
    }

    /**
     * 商品列表 - 查询条件
     *
     * @param request
     * @param lambdaQueryWrapper
     */
    private void queryShopProductCondition(IndexStoreProductSearchRequest request, LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper) {
        // 查询商户信息(redis获取)
//        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(request.getMerId());
        // 解析权限内json数据
//        List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
//        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
//        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        // 品牌过滤
//        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(brandIdsList), StoreProduct::getBrandId, brandIdsList);
        // 商品id过滤
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(request.getProductIdList()), StoreProduct::getId, request.getProductIdList());

        // 发货地过滤
//        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(tempIdList), StoreProduct::getTempId, tempIdList);
        // 商户对应自建供应商
//        Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
//        lambdaQueryWrapper.and(
//                e -> e.eq(StoreProduct::getSuppliersId, supplier != null ? supplier.getId().toString() : 0)
//                        .or(
//                                i -> i.in(CollectionUtils.isNotEmpty(suppliersIdList), StoreProduct::getSuppliersId, suppliersIdList).and(
//                                        a -> a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
//                                                .or(b -> b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).isNotNull(StoreProduct::getConvertIsEurope))
//                                )
//                        )
//        );
//    	lambdaQueryWrapper.and(a->a.and(e->e.in(CollectionUtils.isNotEmpty(suppliersIdList),StoreProduct::getSuppliersId, suppliersIdList).ne(StoreProduct::getIsEurope,1))
//    			.or(null != supplier,e->e.eq(StoreProduct::getIsEurope,1).eq(StoreProduct::getSuppliersId,supplier.getId())));
//        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
//            Supplier supplier = supplierService.getSupplierBarcode(request.getMerId());
//            if (null != supplier) {
//                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
//                suppliersIdList.add(supplier.getId().toString());
//            }
//            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, suppliersIdList);
//        }

        //必要条件
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        // 查询商户上架商品
        lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(request.getMerId()) + " WHERE is_not_show = 0");
        // 搜索关键词
        String keywords = request.getKeywords();
        if (StringUtils.isNotBlank(keywords)) {
            lambdaQueryWrapper.and(wrap -> wrap
                    .apply("LOCATE({0},keyword)>0 OR LOCATE({0}, store_name)>0 OR LOCATE({0}, brand_name)>0", keywords));
        }
        // 意大利轮播图-商品列表(应该失效了)
        if (BooleanUtil.isTrue(request.getIsEurope())) {
            lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.EUROPE.getCode());
        }
        // 发货地
        if (StringUtils.isNotBlank(request.getStockArea())) {
            List<Integer> stockAreaList = new ArrayList<>();
            String[] strAreas = request.getStockArea().split(",");
            for (String s : strAreas) {
                stockAreaList.add(Integer.parseInt(s));
            }
            if (stockAreaList.size() == 1) {
                lambdaQueryWrapper.eq(StoreProduct::getTempId, stockAreaList.get(0));
            } else {
                lambdaQueryWrapper.in(StoreProduct::getTempId, stockAreaList);
            }
        }
        // 图搜BarCode
        if (CollectionUtils.isNotEmpty(request.getBarCodeArr())) {
            lambdaQueryWrapper.in(StoreProduct::getBarCode, request.getBarCodeArr());
        }
        // 新增条件最低高价格 最大小库存
        if (request.getMinPrice() != null || request.getMaxPrice() != null) {
            MarkupRateRequest rateRequest = new MarkupRateRequest();
            rateRequest.setMerId(request.getMerId());
            rateRequest.setType(MarkupRateTypeEnum.PLAT_平台加价率.getType());
            BigDecimal platRatio = markupRateService.selectMerchantRatio(rateRequest);
            rateRequest.setType(MarkupRateTypeEnum.MERCHANT_商户加价率.getType());
            BigDecimal merRatio = markupRateService.selectMerchantRatio(rateRequest);
            if (request.getMinPrice() != null && request.getMaxPrice() == null) {
                lambdaQueryWrapper.ge(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMinPrice(), platRatio, merRatio));
            } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.le(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMaxPrice(), platRatio, merRatio));
            } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.between(StoreProduct::getPrice, UnitConvertUtil.getRequestPrice(request.getMinPrice(), platRatio, merRatio), UnitConvertUtil.getRequestPrice(request.getMaxPrice(), platRatio, merRatio));
            }
        }
        // 新品
        if (request.getIsNew() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getIsNew, request.getIsNew());
        }
        // 上架
        if (request.getIsShow() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getIsShow, request.getIsShow());
        }
        // 品牌或品牌列表
        if (request.getBrandId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if (StringUtils.isNotBlank(request.getBrandIds())) {
            String[] brds = request.getBrandIds().split(",");
            lambdaQueryWrapper.in(StoreProduct::getBrandId, Arrays.asList(brds));
        }
        // 供应商
        if (StringUtils.isNotBlank(request.getSuppliersIds())) {
            String[] suppliersIds = request.getSuppliersIds().split(",");
            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, Arrays.asList(suppliersIds));
        }
        // 类目
        if (CollectionUtils.isNotEmpty(request.getCateId())) {
            lambdaQueryWrapper.in(StoreProduct::getCateId, request.getCateId());
        }
        // 过滤禁用或失效分类
        if (Objects.nonNull(request.getMerId())) {
            List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(request.getMerId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);
        }
        // 精选/小编推荐
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(request.getMerId()) + " WHERE is_best = 1 AND is_not_show = 0");
        }
        // 折扣价查询条件
        if (request.getMinDiscount() != null && request.getMaxDiscount() == null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 >= {0} ", request.getMinDiscount());
        } else if (request.getMinDiscount() == null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 <= {0} ", request.getMaxDiscount());
        } else if (request.getMinDiscount() != null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("round(price / (ot_price * exchange_rate),2) * 10 BETWEEN  {0} and {1} ", request.getMinDiscount(), request.getMaxDiscount());
        }
        // 销量排序
        if (StringUtils.isNotBlank(request.getSalesOrder())) {
            if (request.getSalesOrder().equals(Constants.SORT_DESC)) {
                lambdaQueryWrapper.orderByDesc(StoreProduct::getSales);
            } else {
                lambdaQueryWrapper.orderByAsc(StoreProduct::getSales);
            }
        }
        // 价格排序
        if (StringUtils.isNotBlank(request.getPriceOrder())) {
            if (request.getPriceOrder().equals(Constants.SORT_DESC)) {
                lambdaQueryWrapper.orderByDesc(StoreProduct::getPrice);
            } else {
                lambdaQueryWrapper.orderByAsc(StoreProduct::getPrice);
            }
        }
        // 折扣排序 放在最后
        if (StringUtils.isNotBlank(request.getDiscountSort())) {
            if (StringUtils.isBlank(request.getPriceOrder()) && StringUtils.isBlank(request.getSalesOrder())) {
                lambdaQueryWrapper.last(" order by round(price / (ot_price * exchange_rate),2) * 10 " + request.getDiscountSort());
            } else {
                lambdaQueryWrapper.last(",round(price / (ot_price * exchange_rate),2) * 10 " + request.getDiscountSort());
            }
        } else {
            // 推送时间排序
            lambdaQueryWrapper.orderByDesc(StoreProduct::getLastPushTime);
        }
        // 用户优惠券跳转
        if (null != request.getUserCouponId()) {
            StoreCouponUser storeCouponUser = frontCouponUserService.getById(request.getUserCouponId());
            if (null != storeCouponUser) {
                if (CouponUseTypeEnum.GOODS.getCode().equals(storeCouponUser.getUseType())) {
                    List<Integer> productIds = frontCouponUserService.listCouponUserProductId(storeCouponUser.getCouponId());
                    lambdaQueryWrapper.in(StoreProduct::getId, productIds);
                } else if (CouponUseTypeEnum.CATE.getCode().equals(storeCouponUser.getUseType()) && StringUtils.isNotBlank(storeCouponUser.getPrimaryKey())) {
                    CouponProductRangeDTO couponProductRangeDTO = com.alibaba.fastjson.JSONObject.parseObject(storeCouponUser.getPrimaryKey(), CouponProductRangeDTO.class);
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getCateIds()), StoreProduct::getCateId, couponProductRangeDTO.getCateIds());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getTempIds()), StoreProduct::getTempId, couponProductRangeDTO.getTempIds());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getSeasons()), StoreProduct::getSeasonCode, couponProductRangeDTO.getSeasons());
                    lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(couponProductRangeDTO.getBrandids()), StoreProduct::getBrandId, couponProductRangeDTO.getBrandids());
                }
            }
        }
        // 季节
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(request.getSeason()), StoreProduct::getSeasonCode, request.getSeason());
    }

    /**
     * 商品列表 - 查询条件
     *
     * @param request
     * @param lambdaQueryWrapper
     */
    private void queryConditionV2(IndexStoreProductSearchRequest request, LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper) {
        // 商品id过滤
        lambdaQueryWrapper.in(CollectionUtils.isNotEmpty(request.getProductIdList()), StoreProduct::getId, request.getProductIdList());

    }

    private List<Integer> getNormLIdListByKeyword(String keywords) {
        return storeProductNormDAO.selectList(Wrappers.<StoreProductNorm>lambdaQuery()
                .like(StoreProductNorm::getKeyword, keywords)).stream().map(obj -> obj.getId()).collect(Collectors.toList());
    }

    /**
     * 根据分类名称获得分类id
     *
     * @param keywords
     * @return
     */
    private List<Integer> getCateIdListByCateName(String keywords) {
        if (keywords.matches(".*?[a-zA-Z]+.*?")) {
            //全部小写
            keywords = keywords.toLowerCase();
        }
        return categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().eq(CategoryMatch::getType, 1).like(CategoryMatch::getName, keywords))
                .stream().map(CategoryMatch::getId).collect(Collectors.toList());
    }

    /**
     * 商品列表 - 获取商品id
     *
     * @param keywords
     * @return
     */
    private Integer getProductIdByKeywords(String keywords) {
        Integer productId = null;
        if (CrmebUtil.isString2Num(keywords) && 9 > keywords.length()) {
            productId = Integer.valueOf(keywords);
        }
        return productId;
    }

    /**
     * 商品列表 - 根据品牌名称, 获取品牌id
     *
     * @param brandName
     * @return
     */
    private List<Integer> getOneByBrandName(String brandName) {

        if (brandName.matches(".*?[a-zA-Z]+.*?")) {
            //全部小写
            brandName = brandName.toLowerCase();
        }

        return storeBrandService.brandIdlist(brandName);
    }


    /**
     * 设置优惠券信息
     *
     * @param storeProductRequest 商品request信息
     * @param storeProduct        商品信息
     */
    private void shipProductCoupons(StoreProductRequest storeProductRequest, StoreProduct storeProduct) {
        if (null != storeProductRequest.getCouponIds() && storeProductRequest.getCouponIds().size() > 0) {
            storeProductCouponService.deleteByProductId(storeProduct.getId());
            List<StoreProductCoupon> spcs = new ArrayList<>();
            for (Integer couponId : storeProductRequest.getCouponIds()) {
//                StoreProductCoupon spc = new StoreProductCoupon(storeProduct.getId(), couponId, DateUtil.getNowTime());
//                spcs.add(spc);
            }
            storeProductCouponService.saveCoupons(spcs);
        }
    }

    /**
     * 计算产品属性之中最大和最小的价格，新增和编辑使用
     *
     * @param storeProductRequest 分析的参数
     * @param storeProduct        当前操作的产品
     */
    private void calcPriceForAttrValues(StoreProductRequest storeProductRequest, StoreProduct storeProduct) {
        // 设置商品成本价和市场价，成本价=sku配置的最低价，商品价格=sku配置的最高价格
        //        BigDecimal costPrice = storeProductRequest.getAttrValue()
        //                    .stream().map(e->e.getCost()).reduce(BigDecimal.ZERO,BigDecimal::add);
        if (CollectionUtils.isEmpty(storeProductRequest.getAttrValue())) {
            throw new CrmebException("请输入商品sku规格属性");
        }
        List<StoreProductAttrValueRequest> attrValues = storeProductRequest.getAttrValue();
        if (attrValues.stream().anyMatch(e -> e.getPrice() == null || e.getPrice().compareTo(BigDecimal.ZERO) < 0)) {
            throw new CrmebException("售价不能为空或小于0");
        }
        if (attrValues.stream().anyMatch(e -> e.getCost() == null || e.getCost().compareTo(BigDecimal.ZERO) < 0)) {
            throw new CrmebException("成本价不能为空或小于0");
        }
        if (attrValues.stream().anyMatch(e -> e.getOtPrice() == null || e.getOtPrice().compareTo(BigDecimal.ZERO) < 0)) {
            throw new CrmebException("原价不能为空或小于0");
        }
        if (attrValues.stream().anyMatch(e -> e.getStock() == null || e.getStock() < 0)) {
            throw new CrmebException("库存不能为空或小于0");
        }
        // 不要显示成本价，显示最低sku售价
        double costPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getCost().doubleValue()).min().orElse(0);
        //总库存
        int stock = storeProductRequest.getAttrValue().stream().mapToInt(StoreProductAttrValueRequest::getStock).sum();
        //原成本价
        BigDecimal sourceCost = storeProductRequest.getSourceCost();
        double sellPrice, otPrice;
        if (stock > 0) {
            sellPrice = storeProductRequest.getAttrValue().stream().filter(e -> e.getStock() > 0).mapToDouble(e -> e.getPrice().doubleValue()).min().orElse(0);
            // 原价
            otPrice = storeProductRequest.getAttrValue().stream().filter(e -> e.getStock() > 0).mapToDouble(e -> e.getOtPrice().doubleValue()).min().orElse(0);
        } else {
            sellPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getPrice().doubleValue()).min().orElse(0);
            otPrice = storeProductRequest.getAttrValue().stream().mapToDouble(e -> e.getOtPrice().doubleValue()).min().orElse(0);
        }
        storeProduct.setCost(BigDecimal.valueOf(costPrice));
        storeProduct.setSourceCost(BigDecimal.valueOf(costPrice));
        storeProduct.setPrice(BigDecimal.valueOf(sellPrice));
        storeProduct.setOtPrice(BigDecimal.valueOf(otPrice));
        storeProduct.setStock(stock);
    }

    private String getDraftProductBarCode(Integer merId) {
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        String barCode = supplier.getBarcode();
        ProductRequest request = new ProductRequest();
        request.setMinBarCode(Integer.valueOf(barCode));
        StoreProductDraft storeProduct = storeProductDAO.selectDraftProductOne(request);
        if (null == storeProduct) {
            barCode = barCode + "000000";
        } else {
            barCode = storeProduct.getBarCode().split("-")[0];
            barCode = barCode.length() > 10 ? barCode.substring(0, 10) : barCode;
            Integer code = Integer.valueOf(barCode) + 1;
            barCode = code.toString();
        }
        log.info("自建商品生成barCode:{}", barCode);
        return barCode;
    }

    private String getProductBarCode(Integer merId) {
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        String barCode = supplier.getBarcode();
        ProductRequest request = new ProductRequest();
        request.setMinBarCode(Integer.valueOf(barCode));
        StoreProduct storeProduct = storeProductDAO.selectProductOne(request);
        if (null == storeProduct) {
            barCode = barCode + "000000";
        } else {
            barCode = storeProduct.getBarCode().split("-")[0];
            barCode = barCode.length() > 10 ? barCode.substring(0, 10) : barCode;
            Integer code = Integer.valueOf(barCode) + 1;
            barCode = code.toString();
        }
        log.info("自建商品生成barCode:{}", barCode);
        return barCode;
    }

    @Override
    public PageInfo<StoreProductResponse> getList(StoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        Page<StoreProduct> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 StoreProduct 类的多条件查询
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //类型搜索
        switch (request.getType()) {
            case 1:
                //出售中（已上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                // 库存为0的商品不显示在出售中列表
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                //仓库中（未上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            default:
                break;
        }

        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i.or()
                    .eq(NumberUtil.isInteger(request.getKeywords()), StoreProduct::getId, request.getKeywords())
                    .or().like(StoreProduct::getStoreName, request.getKeywords())
                    .or().like(StoreProduct::getKeyword, request.getKeywords())
                    .or().like(StoreProduct::getBarCode, request.getKeywords())
            );
        }
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.eq(StoreProduct::getIsBest, true);
        }

        if (null != request.getIsEurope()) {
            lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.EUROPE.getCode());
        }

        //判断是否供应商筛选
        if (request.getSupplierId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getSuppliersId, request.getSupplierId());
        }

        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            lambdaQueryWrapper.in(StoreProduct::getTempId, request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", request.getCateId()));
        }

        //新增条件最低高价格 最大小库存
        if (request.getMinPrice() != null && request.getMaxPrice() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getPrice, request.getMinPrice());
        } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.le(StoreProduct::getPrice, request.getMaxPrice());
        } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.between(StoreProduct::getPrice, request.getMinPrice(), request.getMaxPrice());
        }

        if (request.getMinStock() != null && request.getMaxStock() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getStock, request.getMinStock());
        } else if (request.getMinStock() == null && request.getMaxStock() != null) {
            lambdaQueryWrapper.le(StoreProduct::getStock, request.getMaxStock());
        } else if (request.getMinStock() != null && request.getMaxStock() != null) {
            lambdaQueryWrapper.between(StoreProduct::getStock, request.getMinStock(), request.getMaxStock());
        }

        lambdaQueryWrapper.eq(StoreProduct::getMerId, request.getMerId());
        lambdaQueryWrapper.or(i -> i.or().eq(StoreProduct::getMerId, request.getMerId()).eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE.getCode()));

        lambdaQueryWrapper.orderByDesc(StoreProduct::getId);
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }
        // 匹配详情属性(此处应该不需要, 要的话就开启即可 author: daigb)
        // productConvertUtil.convertProduct(storeProducts);
        productConvertUtil.convertProductImage(storeProducts);

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> ids = storeProducts.stream().map(p -> p.getId()).collect(Collectors.toList());
        // 处理attr数据
        List<StoreProductAttr> attrs = attrService.list(Wrappers.<StoreProductAttr>lambdaQuery()
                .in(StoreProductAttr::getProductId, ids)
        );
        Map<Integer, List<StoreProductAttr>> attrMap = attrs.stream().collect(Collectors.toMap(StoreProductAttr::getProductId,
                s -> {
                    List<StoreProductAttr> list = new ArrayList<StoreProductAttr>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttr> value1, List<StoreProductAttr> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        // 处理attrvalue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, ids)
        );
        Map<Integer, List<StoreProductAttrValueResponse>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValueResponse> list = new ArrayList<StoreProductAttrValueResponse>();
                    StoreProductAttrValueResponse response = new StoreProductAttrValueResponse();
                    BeanUtils.copyProperties(s, response);
                    list.add(response);
                    return list;
                },
                (List<StoreProductAttrValueResponse> value1, List<StoreProductAttrValueResponse> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        // 处理description数据
        List<StoreProductDescription> descriptions = storeProductDescriptionService.list(Wrappers.<StoreProductDescription>lambdaQuery()
                .in(StoreProductDescription::getProductId, ids)
        );
        Map<Integer, String> descriptionMap = descriptions.stream().collect(Collectors.toMap(StoreProductDescription::getProductId,
                StoreProductDescription::getDescription,
                (value1, value2) -> {
                    return value2;
                }));
        // 处理category数据
        List<Category> categorys = categoryService.list();
        Map<Integer, Category> categoryMap = categorys.stream().collect(Collectors.toMap(Category::getId, s -> s));
        // 处理收藏数据
        List<StoreProductRelation> relations = storeProductRelationService.list(Wrappers.<StoreProductRelation>lambdaQuery()
                .eq(StoreProductRelation::getType, "collect")
        );
        Map<Integer, Long> relationMap = relations.stream().collect(Collectors.groupingBy(StoreProductRelation::getProductId, Collectors.counting()));

        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);

            // 查询对应属性赋值
            storeProductResponse.setAttr(attrMap.get(id));
            storeProductResponse.setAttrValue(attrValueMap.get(id));
            storeProductResponse.setContent(null == descriptionMap.get(id) ? "" : descriptionMap.get(id));
            // 商品标签处理
            List<Integer> productCateIds = Collections.singletonList(product.getCateId());
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < productCateIds.size(); i++) {
                Category category = categoryMap.get(productCateIds.get(i));
                sb.append(null == category ? "" : category.getName());
                if (i < productCateIds.size() - 1) {
                    sb.append(",");
                }
            }
            storeProductResponse.setCateValues(sb.toString());
            // 商品收藏数
            storeProductResponse.setCollectCount(null == relationMap.get(id) ? 0 : relationMap.get(id).intValue());

            // 价格相关计算
            storeProductResponse.setOtPrice(priceUtil.eur2RmbStatic(storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate()));
            //storeProductResponse.setCost(priceUtil.hk2Rmb(storeProductResponse.getCost()));
            if (CollectionUtils.isNotEmpty(storeProductResponse.getAttrValue())) {
                storeProductResponse.getAttrValue().forEach(attrVal -> {
                    //attrVal.setCost(priceUtil.hk2Rmb(attrVal.getCost()));
                    attrVal.setOtPrice(priceUtil.eur2RmbStatic(attrVal.getOtPrice(), storeProductResponse.getExchangeRate()));
                });
                //库存为0列表也展示商品属性值
                //storeProductResponse.setAttrValue(storeProductResponse.getAttrValue().stream().filter(e->e.getStock()>0).collect(Collectors.toList()));
            }
            // 未设置运费，发货地是海外的时候 按售价百分比计算运费算运费
            if (StockAreaTempEnum.getByTempId(storeProductResponse.getTempId()).equals(StockAreaTempEnum.EUR)) {
                // 收货地是国内 , 计算运费
                String postRate = StringUtils.defaultString(systemConfigService.getValueByKey(Constants.SYSTEM_CONFIG_POSTAGE_RATE), Constants.DEFAULT_POSTAGE_RATE);
                BigDecimal postage = null == storeProductResponse.getPostage() ? BigDecimal.ZERO : storeProductResponse.getPostage();
                BigDecimal postageSum = postage.add(storeProductResponse.getPrice().multiply(new BigDecimal(postRate).movePointLeft(2)).setScale(2, BigDecimal.ROUND_UP));
                storeProductResponse.setPostage(postageSum);
            }

            storeProductResponses.add(storeProductResponse);
        }

        /******** end *******/

        // 多条sql查询处理分页正确
        return CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
    }

    /**
     * 分页查询sku
     */
    @Override
    @RateLimiter(qps = 20, timeout = 1, timeUnit = TimeUnit.SECONDS)
    public PageInfo<StoreProductAttrValueResponse> selectSkuPage(StoreProductSearchRequest request) {
        Page<Object> page = PageHelper.startPage(request.getPageNow(), request.getPageSize());
        List<StoreProductAttrValueResponse> storeBrandResponses = storeProductAttrValueDAO.selectSkuPage(request);

        return CommonPage.copyPageInfo(page, storeBrandResponses);
    }

    /**
     * 标准商品分页列表
     */
    @Override
    public PageInfo<StoreProduct> getNormList(StoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        // 组装条件
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //类型搜索
        switch (request.getType()) {
            case 1:
                //出售中（已上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                // 库存为0的商品不显示在出售中列表
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                //仓库中（未上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            default:
                break;
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
//            // 查询是否一级分类
//            CategoryMatch categoryMatch = categoryMatchService.getById(request.getCateId());
//            String cateIdStr = request.getCateId();
//            if(0 == categoryMatch.getPid()) {
//                List<Integer> cateIds = categoryMatchService.getChildVoListByPid(categoryMatch.getId()).stream().map(CategoryMatch::getId).collect(Collectors.toList());
//                cateIdStr = StringUtils.join(cateIds, ",");
//            }
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
        // 关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i.or().eq(NumberUtil.isInteger(request.getKeywords()), StoreProduct::getId, request.getKeywords())
                    .or().like(StoreProduct::getStoreName, request.getKeywords())
                    .or().like(StoreProduct::getKeyword, request.getKeywords())
                    .or().like(StoreProduct::getBarCode, request.getKeywords())
            );
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        // 新增条件最低高价格
        if (request.getMinPrice() != null && request.getMaxPrice() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getPrice, request.getMinPrice());
        } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.le(StoreProduct::getPrice, request.getMaxPrice());
        } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
            lambdaQueryWrapper.between(StoreProduct::getPrice, request.getMinPrice(), request.getMaxPrice());
        }
        // 最大小库存
        if (request.getMinStock() != null && request.getMaxStock() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getStock, request.getMinStock());
        } else if (request.getMinStock() == null && request.getMaxStock() != null) {
            lambdaQueryWrapper.le(StoreProduct::getStock, request.getMaxStock());
        } else if (request.getMinStock() != null && request.getMaxStock() != null) {
            lambdaQueryWrapper.between(StoreProduct::getStock, request.getMinStock(), request.getMaxStock());
        }
        lambdaQueryWrapper.orderByDesc(StoreProduct::getId);

        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        PageInfo<StoreProduct> pageInfo = PageInfo.of(storeProducts);

        return pageInfo;
    }

    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<StoreProduct>
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @Override
    public PageInfo<StoreProductResponse> getMerchnatList2(StoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer merId) {
        long a = System.currentTimeMillis();
        log.info("--------------- 查询商品列表, 当前的商户merId: {}, 查询条件: {} ---------------", merId, JSON.toJSONString(request));
        StoreProductQueryDto queryDto = getStoreProductQuery(request, merId);
        Page<StoreProduct> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
//        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
        log.info("商户查询商品列表sql参数:{}", JSON.toJSONString(queryDto));
        List<StoreProduct> storeProducts = storeProductDAO.queryProductList(queryDto);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
        }

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        // 匹配详情属性(只在活动列表里面查询)
        if (BooleanUtil.isTrue(request.getMerUse())) {
            productConvertUtil.convertProduct(storeProducts);
        } else {
            productConvertUtil.convertProductImage(storeProducts);
        }
        //查询加价率
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());
        List<Integer> recommendProductIdList = new ArrayList<>();
        // 平台推荐商品
        List<StoreZone> storeZoneList = storeZoneService.list(Wrappers.lambdaQuery(StoreZone.class)
                .eq(StoreZone::getMerId, merId)
                .gt(StoreZone::getEndTime, new Date())
                .isNotNull(StoreZone::getPushZoneId)
        );
        if (CollectionUtils.isNotEmpty(storeZoneList)) {
            List<Integer> zoneIdList = storeZoneList.stream().map(StoreZone::getPushZoneId).collect(Collectors.toList());
            List<StoreZoneProduct> storeZoneProductList = storeZoneProductService.list(Wrappers.lambdaQuery(StoreZoneProduct.class)
                    .in(StoreZoneProduct::getZoneId, zoneIdList)
            );
            recommendProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
        }

        //查询商户是否开启会员指定商品折扣
        MerchantMemberBenefits merchantMemberBenefits = merchantMemberBenefitsService.getOne(Wrappers.lambdaQuery(MerchantMemberBenefits.class)
                .eq(MerchantMemberBenefits::getMerId, merId)
                .eq(MerchantMemberBenefits::getEquityEnableFlag, true)
                .eq(MerchantMemberBenefits::getEquityType, EquityTypeEnum.DISCOUNT.getCode())
                .eq(MerchantMemberBenefits::getDiscountConditions, 2));
        List<Integer> discountList = new ArrayList<>();
        if (Objects.nonNull(merchantMemberBenefits)) {
            List<StoreProductDiscount> productDiscountList = storeProductDiscountService.list(Wrappers.lambdaQuery(StoreProductDiscount.class)
                    .eq(StoreProductDiscount::getMerId, merId).in(StoreProductDiscount::getProductId, ids));
            discountList = productDiscountList.stream().map(StoreProductDiscount::getProductId).collect(Collectors.toList());
        }

        // 需要查询满减送商品
        List<Integer> channelDiscountIds = new ArrayList<>();
        boolean isCheckedGoods = false; // 是否有配置
        boolean isAllGoods = false; // 全部商品参与活动
        List<Integer> inGoodsId = new ArrayList<>(); // 参与商品列表
        List<Integer> exceptionGoodsId = new ArrayList<>(); // 不参与商品列表
        if (BooleanUtil.isTrue(request.getIsDiscount())) {
            // 查询商户所有未结束的满减送活动
            List<ChannelDiscount> channelDiscounts = channelDiscountService.list(Wrappers.<ChannelDiscount>lambdaQuery()
                    .select(ChannelDiscount::getId)
                    .eq(ChannelDiscount::getMerId, merId)
                    .eq(ChannelDiscount::getStatus, true)
                    .ne(null != request.getDiscountId(), ChannelDiscount::getId, request.getDiscountId())
                    .ge(ChannelDiscount::getEndTime, new Date())
            );
            for (ChannelDiscount channelDiscount : channelDiscounts) {
                isCheckedGoods = true;
                // 有全部商品参加活动情况
                if (1 == channelDiscount.getGoodsType()) {
                    isAllGoods = true;
                    break;
                }

                channelDiscountIds.add(channelDiscount.getId());
            }
            if (!isAllGoods && CollectionUtils.isNotEmpty(channelDiscountIds)) {
                // 修改则不包含当前活动商品, 新增则为所有活动商品
                List<ChannelDiscountGoods> channelDiscountGoodsList = channelDiscountGoodsService.list(Wrappers.<ChannelDiscountGoods>lambdaQuery()
                        .select(ChannelDiscountGoods::getGoodsId)
                        .eq(ChannelDiscountGoods::getType, 1)
                        .in(ChannelDiscountGoods::getDiscountId, channelDiscountIds)
                );
                // 拆分参与活动商品id和不参与活动商品id
                for (ChannelDiscountGoods channelDiscountGoods : channelDiscountGoodsList) {
                    if (3 == channelDiscountGoods.getGoodsType()) {
                        exceptionGoodsId.add(channelDiscountGoods.getGoodsId());
                    } else if (2 == channelDiscountGoods.getGoodsType()) {
                        inGoodsId.add(channelDiscountGoods.getGoodsId());
                    }
                }
            }
        }

        // 推送关联数据
        MerPlatEnums enumByMerId = MerPlatEnums.getEnumByMerId(merId);
        List<Relation> productRelations = relationService.list(Wrappers.<Relation>lambdaQuery().in(Relation::getBusinessCode, ids.stream().map(String::valueOf).collect(Collectors.toList()))
                .eq(Relation::getBusinessType,
                        enumByMerId == null?MerPlatEnums.OTHER.getBusinessType().getCode():enumByMerId.getBusinessType().getCode()));
        Map<String, Relation> relationsMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(productRelations)){
            relationsMap = productRelations.stream().collect(Collectors.toMap(Relation::getBusinessCode, v -> v));
        }

        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            // 对象复制
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            if (MapUtils.isNotEmpty(relationsMap) && relationsMap.containsKey(String.valueOf(product.getId()))){
                Relation relation = relationsMap.get(String.valueOf(product.getId()));
                // 推送状态
                storeProductResponse.setPushPlatDesc(PlatPushStatusEnums.getDescByCode(enumByMerId == null?MerPlatEnums.OTHER.getPlatUp().getCode():relation.getSubCode()));
            }else {
                storeProductResponse.setPushPlatDesc(PlatPushStatusEnums.PUSH_WAIT.getDesc());
            }

            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            if (recommendProductIdList.contains(id)) {
                storeProductResponse.setIsRecommend(true);
            }
            //设置商品是否会员折扣
            storeProductResponse.setMemberDiscountFlag(discountList.contains(storeProductResponse.getId()));

            // 满减送商品状态查询
            if (BooleanUtil.isTrue(request.getIsDiscount()) && isCheckedGoods) {
                boolean otherDiscount = false;
                // 所有商品参与
                if (isAllGoods) {
                    otherDiscount = true;
                    // 指定商品不参与
                } else if (!exceptionGoodsId.contains(id)) {
                    otherDiscount = true;
                    // 指定商品参与
                } else if (inGoodsId.contains(id)) {
                    otherDiscount = true;
                }
                storeProductResponse.setOtherDiscount(otherDiscount);
            }

            storeProductResponses.add(storeProductResponse);
        }
        List<Supplier> visibleSupplier = supplierService.getVisibleSupplier(merId);
        storeProductResponses.stream().forEach(storeProductResponse -> {
            //判断供应商名称是否商户可见
            if (visibleSupplier.stream().noneMatch(supplier -> Objects.equals(supplier.getId().toString(), storeProductResponse.getSuppliersId() + ""))) {
                storeProductResponse.setSuppliersName(null);
            }
        });
        /******** end *******/
        PageInfo<StoreProductResponse> storeProductResponsePageInfo = CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
        // 处理品牌
        productConvertUtil.assembledPlatInfo(storeProductResponsePageInfo.getList());
        long b = System.currentTimeMillis();
        log.info("云仓商品查询方式二新版，耗时：{}",  (b - a));

        return storeProductResponsePageInfo;
    }

    /**
     * 列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页类参数
     * @return List<StoreProduct>
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @Override
    @RateLimiter(qps = 15, timeout = 1, timeUnit = TimeUnit.SECONDS)
    public PageInfo<StoreProductResponse> getMerchnatList(StoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer merId) {
        try {
            log.info("--------------- 查询商品列表, 当前的商户merId: {}, 查询条件: {} ---------------", merId, JSON.toJSONString(request));
            String uuid = UUID.randomUUID().toString();
            long currStart = System.currentTimeMillis();
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, merId);
            Page<StoreProduct> storeProductPage = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
            String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
            log.info("商户查询商品列表sql参数:{},{}",sqlStr,uuid);
            List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
            if (CollectionUtils.isEmpty(storeProducts)) {
                return CommonPage.copyPageInfo(storeProductPage, new ArrayList<>());
            }
            log.error("商户查询商品列表耗时:{},{}", System.currentTimeMillis() - currStart,uuid);
            currStart = System.currentTimeMillis();

            /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
            List<Integer> ids = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
            // 匹配详情属性(只在活动列表里面查询)
            if (BooleanUtil.isTrue(request.getMerUse())) {
                productConvertUtil.convertProduct(storeProducts);
            } else {
                productConvertUtil.convertProductImage(storeProducts);
            }
            log.error("商户商品转换耗时:{},{}", System.currentTimeMillis() - currStart,uuid);
            currStart = System.currentTimeMillis();
            //查询加价率
            Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());
            List<Integer> recommendProductIdList = new ArrayList<>();
            // 平台推荐商品
            List<StoreZone> storeZoneList = storeZoneService.list(Wrappers.lambdaQuery(StoreZone.class)
                    .eq(StoreZone::getMerId, merId)
                    .gt(StoreZone::getEndTime, new Date())
                    .isNotNull(StoreZone::getPushZoneId)
            );
            if (CollectionUtils.isNotEmpty(storeZoneList)) {
                List<Integer> zoneIdList = storeZoneList.stream().map(StoreZone::getPushZoneId).collect(Collectors.toList());
                List<StoreZoneProduct> storeZoneProductList = storeZoneProductService.list(Wrappers.lambdaQuery(StoreZoneProduct.class)
                        .in(StoreZoneProduct::getZoneId, zoneIdList)
                );
                recommendProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            }

            //查询商户是否开启会员指定商品折扣
            MerchantMemberBenefits merchantMemberBenefits = merchantMemberBenefitsService.getOne(Wrappers.lambdaQuery(MerchantMemberBenefits.class)
                    .eq(MerchantMemberBenefits::getMerId, merId)
                    .eq(MerchantMemberBenefits::getEquityEnableFlag, true)
                    .eq(MerchantMemberBenefits::getEquityType, EquityTypeEnum.DISCOUNT.getCode())
                    .eq(MerchantMemberBenefits::getDiscountConditions, 2));
            List<Integer> discountList = new ArrayList<>();
            if (Objects.nonNull(merchantMemberBenefits)) {
                List<StoreProductDiscount> productDiscountList = storeProductDiscountService.list(Wrappers.lambdaQuery(StoreProductDiscount.class)
                        .eq(StoreProductDiscount::getMerId, merId).in(StoreProductDiscount::getProductId, ids));
                discountList = productDiscountList.stream().map(StoreProductDiscount::getProductId).collect(Collectors.toList());
            }

            // 需要查询满减送商品
            List<Integer> channelDiscountIds = new ArrayList<>();
            boolean isCheckedGoods = false; // 是否有配置
            boolean isAllGoods = false; // 全部商品参与活动
            List<Integer> inGoodsId = new ArrayList<>(); // 参与商品列表
            List<Integer> exceptionGoodsId = new ArrayList<>(); // 不参与商品列表
            if (BooleanUtil.isTrue(request.getIsDiscount())) {
                // 查询商户所有未结束的满减送活动
                List<ChannelDiscount> channelDiscounts = channelDiscountService.list(Wrappers.<ChannelDiscount>lambdaQuery()
                        .select(ChannelDiscount::getId)
                        .eq(ChannelDiscount::getMerId, merId)
                        .eq(ChannelDiscount::getStatus, true)
                        .ne(null != request.getDiscountId(), ChannelDiscount::getId, request.getDiscountId())
                        .ge(ChannelDiscount::getEndTime, new Date())
                );
                for (ChannelDiscount channelDiscount : channelDiscounts) {
                    isCheckedGoods = true;
                    // 有全部商品参加活动情况
                    if (1 == channelDiscount.getGoodsType()) {
                        isAllGoods = true;
                        break;
                    }

                    channelDiscountIds.add(channelDiscount.getId());
                }
                if (!isAllGoods && CollectionUtils.isNotEmpty(channelDiscountIds)) {
                    // 修改则不包含当前活动商品, 新增则为所有活动商品
                    List<ChannelDiscountGoods> channelDiscountGoodsList = channelDiscountGoodsService.list(Wrappers.<ChannelDiscountGoods>lambdaQuery()
                            .select(ChannelDiscountGoods::getGoodsId)
                            .eq(ChannelDiscountGoods::getType, 1)
                            .in(ChannelDiscountGoods::getDiscountId, channelDiscountIds)
                    );
                    // 拆分参与活动商品id和不参与活动商品id
                    for (ChannelDiscountGoods channelDiscountGoods : channelDiscountGoodsList) {
                        if (3 == channelDiscountGoods.getGoodsType()) {
                            exceptionGoodsId.add(channelDiscountGoods.getGoodsId());
                        } else if (2 == channelDiscountGoods.getGoodsType()) {
                            inGoodsId.add(channelDiscountGoods.getGoodsId());
                        }
                    }
                }
            }

            // 推送关联数据
            MerPlatEnums enumByMerId = MerPlatEnums.getEnumByMerId(merId);
            List<Relation> productRelations = relationService.list(Wrappers.<Relation>lambdaQuery().in(Relation::getBusinessCode, ids.stream().map(String::valueOf).collect(Collectors.toList()))
                    .eq(Relation::getBusinessType,
                            enumByMerId == null?MerPlatEnums.OTHER.getBusinessType().getCode():enumByMerId.getBusinessType().getCode()));
            Map<String, Relation> relationsMap = new HashMap<>();
            if (CollectionUtils.isNotEmpty(productRelations)){
                relationsMap = productRelations.stream().collect(Collectors.toMap(Relation::getBusinessCode, v -> v));
            }

            // 循环赋值
            List<StoreProductResponse> storeProductResponses = new ArrayList<>();
            for (StoreProduct product : storeProducts) {
                Integer id = product.getId();
                // 对象复制
                StoreProductResponse storeProductResponse = new StoreProductResponse();
                BeanUtils.copyProperties(product, storeProductResponse);
                if (MapUtils.isNotEmpty(relationsMap) && relationsMap.containsKey(String.valueOf(product.getId()))){
                    Relation relation = relationsMap.get(String.valueOf(product.getId()));
                    // 推送状态
                    storeProductResponse.setPushPlatDesc(PlatPushStatusEnums.getDescByCode(enumByMerId == null?MerPlatEnums.OTHER.getPlatUp().getCode():relation.getSubCode()));
                }else {
                    storeProductResponse.setPushPlatDesc(PlatPushStatusEnums.PUSH_WAIT.getDesc());
                }

                // 通过原价算折扣率 ----处理
                if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                    BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                    if (null != bigDecimal) {
                        storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                    }
                }
                if (recommendProductIdList.contains(id)) {
                    storeProductResponse.setIsRecommend(true);
                }
                //设置商品是否会员折扣
                storeProductResponse.setMemberDiscountFlag(discountList.contains(storeProductResponse.getId()));

                // 满减送商品状态查询
                if (BooleanUtil.isTrue(request.getIsDiscount()) && isCheckedGoods) {
                    boolean otherDiscount = false;
                    // 所有商品参与
                    if (isAllGoods) {
                        otherDiscount = true;
                        // 指定商品不参与
                    } else if (!exceptionGoodsId.contains(id)) {
                        otherDiscount = true;
                        // 指定商品参与
                    } else if (inGoodsId.contains(id)) {
                        otherDiscount = true;
                    }
                    storeProductResponse.setOtherDiscount(otherDiscount);
                }

                storeProductResponses.add(storeProductResponse);
            }
            List<Supplier> visibleSupplier = supplierService.getVisibleSupplier(merId);
            storeProductResponses.stream().forEach(storeProductResponse -> {
                //判断供应商名称是否商户可见
                if (visibleSupplier.stream().noneMatch(supplier -> Objects.equals(supplier.getId().toString(), storeProductResponse.getSuppliersId() + ""))) {
                    storeProductResponse.setSuppliersName(null);
                }
            });
            /******** end *******/
            PageInfo<StoreProductResponse> storeProductResponsePageInfo = CommonPage.copyPageInfo(storeProductPage, storeProductResponses);
            // 处理品牌
            productConvertUtil.assembledPlatInfo(storeProductResponsePageInfo.getList());
            log.error("商户商品处理最终耗时:{},{}", System.currentTimeMillis() - currStart,uuid);
            return storeProductResponsePageInfo;
        }catch (Exception e){
            log.error("查询商品数据异常: ",e);
        }
        return null;

    }

    private StoreProductQueryDto getStoreProductQuery(StoreProductSearchRequest request, Integer merId) {
        StoreProductQueryDto queryDto = new StoreProductQueryDto();

        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (channelMerchant == null) {
            throw new CrmebException("该商户不存在");
        }
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        if (CollectionUtils.isNotEmpty(brandIdsList)) {
            queryDto.setBrandIdsList(brandIdsList);
        }
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            if (null != supplier) {
                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                suppliersIdList.add(supplier.getId().toString());
            }
        }
        if (CollectionUtils.isNotEmpty(tempIdList)) {
            queryDto.setTempIdList(tempIdList);
        }

        boolean inside = ProductTypeEnum.INSIDE.getCode().equals(request.getIsEurope());
        queryDto.setInside(inside ? SwitchEnum.OPEN.getCode() : SwitchEnum.CLOSE.getCode());
        // 自建列表
        if (inside) {

            queryDto.setIsEurope(ProductTypeEnum.INSIDE.getCode());
            queryDto.setMerId(merId);

            //自建商品推送状态
            if (request.getSelfPushStatus() != null) {
                queryDto.setSelfPushStatus(request.getSelfPushStatus());
            }
        } else {
            queryDto.setSuppliersIdList(suppliersIdList);
            queryDto.setIsEurope(ProductTypeEnum.INSIDE.getCode());
            queryDto.setMerId(merId);
        }
        //平台推荐
        queryDto.setPlatformRecommended(request.getPlatformRecommended());
        if (BooleanUtil.isTrue(request.getPlatformRecommended())) {
            List<StoreZone> storeZoneList = storeZoneService.list(Wrappers.lambdaQuery(StoreZone.class).eq(StoreZone::getMerId, merId).isNotNull(StoreZone::getPushZoneId).gt(StoreZone::getEndTime, new Date()));
            List<Integer> zoneIdList = storeZoneList.stream().map(StoreZone::getId).collect(Collectors.toList());
            List<StoreZoneProduct> storeZoneProductList = CollectionUtils.isNotEmpty(zoneIdList) ? storeZoneProductService.list(
                    Wrappers.lambdaQuery(StoreZoneProduct.class)
                            .in(StoreZoneProduct::getZoneId, zoneIdList)
            ) : new ArrayList<>();

            List<Integer> recommendedProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            queryDto.setRecommendedProductIdList(recommendedProductIdList);
        }

        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            queryDto.setKeywords(request.getKeywords());
            if(NumberUtil.isInteger(request.getKeywords())){
                queryDto.setIdEquals(request.getKeywords());
            }
        }

        String tableName = TableNameUtil.getProductMerName(merId);
        queryDto.setTableName(tableName);
        if (BooleanUtil.isTrue(request.getIsBest())) {
            queryDto.setIsBest(SwitchEnum.OPEN.getCode());
        }
        if (null != request.getPremiumType()) {
            queryDto.setPremiumType(request.getPremiumType());

        }
        //推荐图搜索
        if (BooleanUtil.isTrue(request.getRecommendFlag())) {
            queryDto.setRecommendFlag(SwitchEnum.OPEN.getCode());
        }
        //会员折扣商品搜索
        if (BooleanUtil.isTrue(request.getMemberDiscountFlag())) {
            queryDto.setMemberDiscountFlag(SwitchEnum.OPEN.getCode());
        }
        if (request.getZoneId() != null) {
            queryDto.setZoneId(request.getZoneId());
            List<StoreZoneProduct> storeZoneProduct = storeZoneProductService.list(Wrappers.<StoreZoneProduct>lambdaQuery().eq(StoreZoneProduct::getZoneId, request.getZoneId()));
            List<Integer> productIds = storeZoneProduct.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            productIds.add(0);
            queryDto.setProductIds(productIds);
        }

        
        //判断是否供应商筛选
        if (request.getSupplierId() != null) {
            queryDto.setSupplierId(request.getSupplierId());
        }
        if (CollectionUtils.isNotEmpty(request.getSupplierIds())) {
            queryDto.setSupplierIds(request.getSupplierIds());
        }

        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            queryDto.setStockAreas(request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            queryDto.setBrandId(request.getBrandId());
        }
        if (CollectionUtils.isNotEmpty(request.getBrandIds())) {
            queryDto.setBrandIds(request.getBrandIds());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            queryDto.setCateId(request.getCateId());
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            queryDto.setCateIdFirstList(cateIds);
        }
        if (CollectionUtils.isNotEmpty(request.getCateIds())) {
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId -> cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            queryDto.setCateIds(cateIds);
        }

        // 最大小库存
        if (request.getMinStock() != null) {
            queryDto.setMinStock(request.getMinStock());
        }
        if (request.getMaxStock() != null) {
            queryDto.setMaxStock(request.getMaxStock());
        }

        if (null != request.getSeasonCode()) {
            queryDto.setSeasonCode(request.getSeasonCode());
        }

        if (!inside) {
            queryDto.setInside(SwitchEnum.CLOSE.getCode());
            //商户看到的云仓商品都是平台已上架的
            queryDto.setIsShow(true);

        }
        //类型搜索
        queryDto.setType(request.getType());

        //自建商品二手/新品查询

        if (Objects.equals(ProductTypeEnum.INSIDE.getCode(), request.getIsEurope())) {
            queryDto.setIsEurope(ProductTypeEnum.INSIDE.getCode());
            queryDto.setOrderType(request.getOrderType());

        }
        if (CollectionUtils.isNotEmpty(request.getPickingIds())) {
            queryDto.setPickingIds(request.getPickingIds());
        }
        if (CollectionUtils.isNotEmpty(request.getActivityIds())) {
            queryDto.setActivityIds(request.getActivityIds());
        }
        if (request.isSellingBelowCost()) {
            queryDto.setSellingBelowCost(SwitchEnum.OPEN.getCode());
        }
        if (StringUtils.isNotBlank(request.getLabelName())) {
            queryDto.setLabelName(request.getLabelName());
        }
        //过滤分类
        List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(integerList)) {
            queryDto.setCateIdsNotIn(integerList);
        }
        if (StringUtils.isNotBlank(request.getDateLimit())) {
            queryDto.setDateLimit(request.getDateLimit());
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            queryDto.setStartTime(dateLimit.getStartTime());
            queryDto.setEndTime(dateLimit.getEndTime());
        }

        MarkupRateRequest rateRequest = new MarkupRateRequest();
        rateRequest.setMerId(merId);
        rateRequest.setType(MarkupRateTypeEnum.PLAT_平台加价率.getType());
        BigDecimal platRatio = markupRateService.selectMerchantRatio(rateRequest);
        rateRequest.setType(MarkupRateTypeEnum.MERCHANT_商户加价率.getType());
        BigDecimal merRatio = markupRateService.selectMerchantRatio(rateRequest);
        //价格筛选
        if (request.getMinPrice() != null) {
            queryDto.setPriceGe(UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMinPrice()), platRatio, merRatio));
        }
        if (request.getMaxPrice() != null) {
            queryDto.setPriceLe(UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMaxPrice()), platRatio, merRatio));
        }
        //折扣价查询条件
        RatioVo ratioVo = priceUtil.getRatio(channelMerchant);
        BigDecimal multiply = (ratioVo.getPlatRatio().movePointLeft(2).add(BigDecimal.ONE));
        queryDto.setPlatRatio(multiply);
        queryDto.setMinDiscount(request.getMinDiscount());
        queryDto.setMaxDiscount(request.getMaxDiscount());
        queryDto.setCostSort(request.getCostSort());

        BigDecimal agentRatio = BigDecimal.ONE;
        if (ratioVo.getFirstAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getFirstAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        if (ratioVo.getSecondAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getSecondAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        queryDto.setAgentRatio(agentRatio);

        // 商品推送状态筛选
        if (CollectionUtils.isNotEmpty(request.getProductPushStatusList())){

            String pushStatus = request.getProductPushStatusList().get(0);
            String businessType = getBusinessType(pushStatus);
            queryDto.setPushStatus(pushStatus);
            if (StringUtils.isNotBlank(businessType)){
                queryDto.setBusinessType(businessType);
            }
        }

        return queryDto;

    }

    /**
     * 列表
     *
     * @return List<StoreProduct>
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @Override
    public List<StoreProductResponse> getMerchnatList(List<Integer> ids, Integer merId, boolean flag) {
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }

        List<StoreProduct> storeProducts = storeProductDAO.selectList(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, ids));
        if (CollectionUtils.isEmpty(storeProducts)) {
            return new ArrayList<>();
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> productIds = storeProducts.stream().map(p -> p.getId()).collect(Collectors.toList());
        // 处理attrvalue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIds)
        );
        if (CollectionUtils.isEmpty(attrValues)) {
            return null;
        }
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValue> list = new ArrayList<StoreProductAttrValue>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValue> value1, List<StoreProductAttrValue> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        //查询加价率
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());
        //折扣信息
        BigDecimal discountRatio = null;
        List<Integer> memberProductIdList = new ArrayList<>();
        if (flag) {
            //计算会员折扣价格
            Map<BigDecimal, List<Integer>> memberDiscountMap = priceUtil.calcMemberDiscountPrice(storeProducts, merId, false);
            if (CollectionUtils.isNotEmpty(memberDiscountMap)) {
                for (Map.Entry<BigDecimal, List<Integer>> entry : memberDiscountMap.entrySet()) {
                    discountRatio = entry.getKey();
                    memberProductIdList = entry.getValue();
                }
            }
        }
        ChannelMemberLevel userMemberLevel = userService.getUserMemberLevel(userService.getInfo());
        if (userMemberLevel != null) {
            priceUtil.calcMemberLevelProductPrice(storeProducts, channelMerchant, Collections.singletonList(userMemberLevel));
        }
        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        List<StoreProductResponse> storeProductResponseList = new ArrayList<>();
        int i = 0;
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();

            //查询商户商品的上下架状态和推荐状态
//            StoreProductMer merchantStoreProduct = storeProductMerService.getOne(Wrappers.<StoreProductMer>lambdaQuery()
//                    .eq(StoreProductMer::getProductId, id)
//                    .last("LIMIT 1"));
//            if(product.getIsShow()){
//                if(!Objects.isNull(merchantStoreProduct) && Objects.equals("1", merchantStoreProduct.getIsNotShow())){
//                    product.setIsShow(false);
//                }
//            }
//            if(null == merchantStoreProduct){
//                product.setIsBest(false);
//            }else {
//                product.setIsBest(merchantStoreProduct.getIsBest());
//            }

            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
//            if(null != merchantStoreProduct) {
//                storeProductResponse.setRecommendImg(merchantStoreProduct.getRecommendImg());
//                //上架时间
//                storeProductResponse.setShelfTime(merchantStoreProduct.getUpdateTime());
//            }


            // 查询对应属性赋值
//            storeProductResponse.setAttr(attrMap.get(id));
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            if (CollectionUtils.isEmpty(values)) {
                continue;
            }
            priceUtil.calcProductValuePrice(values, merId, product, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
            if (flag) {
                if (discountRatio != null && memberProductIdList.contains(product.getId())) {
                    priceUtil.calcValueMemberDiscountPrice(values, discountRatio, channelMerchant.getAppletType());
                }
            }
            if (userMemberLevel != null) {
                priceUtil.calcMemberLevelValuePrice(values, channelMerchant, Collections.singletonList(userMemberLevel));
            }
            Set<String> set = new HashSet<>();
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value.getAttrValue());
                    List<Object> collect = Stream.of(jsonObject.get("尺寸"), jsonObject.get("尺码"), jsonObject.get("大小"), jsonObject.get("腰带尺寸")).collect(Collectors.toList());
                    collect.removeIf(Objects::isNull);
                    set.add(collect.get(0).toString());
                } catch (Exception e) {
                    log.info("该商品无尺寸信息,商品id：{}", value.getProductId());
                }
            }
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponse.setSizeList(new ArrayList<>(set));

            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            storeProductResponses.add(storeProductResponse);
        }

        for (Integer id : ids) {
            if (CollectionUtils.isEmpty(storeProductResponses)) {
                continue;
            }
            storeProductResponses.stream().forEach(q -> {
                if (q.getId().equals(id)) {
                    storeProductResponseList.add(q);
                }
            });
            if (id == null) {
                storeProductResponseList.add(new StoreProductResponse());
            }
        }

        /******** end *******/

        return storeProductResponseList;
    }


    @Override
    public List<StoreProductResponse> getFrontMerchnatList(List<Integer> ids, Integer merId,Integer  leaderId) {
        String logKey = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        long traceStart = System.currentTimeMillis();
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        log.error("获取商户授权耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();
//        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        lambdaQueryWrapper.in(StoreProduct::getId, ids);
        lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        log.error("获取不显示的类目耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();
        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(cateIdList), StoreProduct::getCateId, cateIdList);
        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
        log.error("getFrontMerchnatList查询sql:{}",sqlStr);

        StoreProductQueryDTO storeProductQueryDTO = new StoreProductQueryDTO();
        productUtil.getChannelMerchantAuthV2(storeProductQueryDTO, merId);
        storeProductQueryDTO.setDel(false);
        storeProductQueryDTO.setShow(true);
        storeProductQueryDTO.setStock(0);
        storeProductQueryDTO.setIds(ids);
        storeProductQueryDTO.setNotCateIdList(cateIdList);
        storeProductQueryDTO.setProductMerTableName(TableNameUtil.getProductMerName(merId));
        List<StoreProduct> storeProducts = storeProductDAO.list(storeProductQueryDTO);
        if (CollectionUtils.isNotEmpty(storeProducts)){
            storeProducts.removeIf(StoreProduct::getIsDel);
        }

//        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        log.error("查询商品数据耗时:{},{},{}",(System.currentTimeMillis()-traceStart),logKey,sqlStr);
        traceStart = System.currentTimeMillis();

        if (CollectionUtils.isEmpty(storeProducts)) {
            return new ArrayList<>();
        }
        // 匹配详情属性
        productConvertUtil.convertProductV3(storeProducts, leaderId);
        log.error("匹配详情属性耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> productIds = storeProducts.stream().map(p -> p.getId()).collect(Collectors.toList());
        // 处理attrvalue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIds)
        );
        if (CollectionUtils.isEmpty(attrValues)) {
            return null;
        }
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValue> list = new ArrayList<StoreProductAttrValue>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValue> value1, List<StoreProductAttrValue> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        //查询加价率
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());
        log.error("计算加价率耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        //折扣信息
        BigDecimal discountRatio = null;
        List<Integer> memberProductIdList = new ArrayList<>();
        //计算会员折扣价格
        Map<BigDecimal, List<Integer>> memberDiscountMap = priceUtil.calcMemberDiscountPrice(storeProducts, merId, false);
        if (CollectionUtils.isNotEmpty(memberDiscountMap)) {
            for (Map.Entry<BigDecimal, List<Integer>> entry : memberDiscountMap.entrySet()) {
                discountRatio = entry.getKey();
                memberProductIdList = entry.getValue();
            }
        }
        ChannelMemberLevel userMemberLevel = userService.getUserMemberLevel(userService.getInfo());
        if (userMemberLevel != null) {
            priceUtil.calcMemberLevelProductPrice(storeProducts, channelMerchant, Collections.singletonList(userMemberLevel));
        }
        log.error("计算折扣耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        List<StoreProductResponse> storeProductResponseList = new ArrayList<>();
        int i = 0;
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            // 查询对应属性赋值
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            if (CollectionUtils.isEmpty(values)) {
                continue;
            }
            priceUtil.calcProductValuePrice(values, merId, product, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
            if (discountRatio != null && memberProductIdList.contains(product.getId())) {
                priceUtil.calcValueMemberDiscountPrice(values, discountRatio, channelMerchant.getAppletType());
            }
            if (userMemberLevel != null) {
                priceUtil.calcMemberLevelValuePrice(values, channelMerchant, Collections.singletonList(userMemberLevel));
            }
            Set<String> set = new LinkedHashSet<>();
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value.getAttrValue());
                    List<Object> collect = Stream.of(jsonObject.get("尺寸"), jsonObject.get("尺码"), jsonObject.get("大小"), jsonObject.get("腰带尺寸")).collect(Collectors.toList());
                    collect.removeIf(Objects::isNull);
                    set.add(collect.get(0).toString());
                } catch (Exception e) {
                    log.info("该商品无尺寸信息,商品id：{}", value.getProductId());
                }
            }
            //设置首页收藏标识
            User user = userService.getInfo();
            if (null != user && null != user.getUid()) {
                storeProductResponse.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, false).size() > 0);
            }
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponse.setSizeList(new ArrayList<>(set));
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            // 添加品牌logo
            StoreBrand brand = storeBrandService.getById(storeProductResponse.getBrandId());
            storeProductResponse.setBrandImage(brand.getLogo());

            storeProductResponses.add(storeProductResponse);
        }
        log.error("循环赋值计算耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);

        for (Integer id : ids) {
            if (CollectionUtils.isEmpty(storeProductResponses)) {
                continue;
            }
            storeProductResponses.stream().forEach(q -> {
                if (q.getId().equals(id)) {
                    storeProductResponseList.add(q);
                }
            });
            if (id == null) {
                storeProductResponseList.add(new StoreProductResponse());
            }
        }
        long end = System.currentTimeMillis();
        log.error("MerStoreProductServiceImpl.getFrontMerchnatList,整体耗时: {}",(end-start));
        log.info("供应商商品查询方式一原版，耗时：{}",  (end-start));
        return storeProductResponseList;
    }

    @Override
    public List<StoreProductResponse> getFrontMerchnatList2(List<Integer> ids, Integer merId) {

        String logKey = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        long traceStart = System.currentTimeMillis();
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        log.error("获取商户授权耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();
//        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        lambdaQueryWrapper.in(StoreProduct::getId, ids);
        lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
        List<Integer> cateIdList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        log.error("获取不显示的类目耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();
        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(cateIdList), StoreProduct::getCateId, cateIdList);
        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
        log.error("getFrontMerchnatList查询sql:{}",sqlStr);

        StoreProductQueryDTO storeProductQueryDTO = new StoreProductQueryDTO();
        productUtil.getChannelMerchantAuthV2(storeProductQueryDTO, merId);
        storeProductQueryDTO.setDel(false);
        storeProductQueryDTO.setShow(true);
        storeProductQueryDTO.setStock(0);
        storeProductQueryDTO.setIds(ids);
        storeProductQueryDTO.setNotCateIdList(cateIdList);
        storeProductQueryDTO.setProductMerTableName(TableNameUtil.getProductMerName(merId));
        List<StoreProduct> storeProducts = storeProductDAO.list(storeProductQueryDTO);
        if (CollectionUtils.isNotEmpty(storeProducts)){
            storeProducts.removeIf(StoreProduct::getIsDel);
        }

//        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        log.error("查询商品数据耗时:{},{},{}",(System.currentTimeMillis()-traceStart),logKey,sqlStr);
        traceStart = System.currentTimeMillis();

        if (CollectionUtils.isEmpty(storeProducts)) {
            return new ArrayList<>();
        }
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProducts);
        log.error("匹配详情属性耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> productIds = storeProducts.stream().map(p -> p.getId()).collect(Collectors.toList());
        // 处理attrvalue数据
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIds)
        );
        if (CollectionUtils.isEmpty(attrValues)) {
            return null;
        }
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValue> list = new ArrayList<StoreProductAttrValue>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValue> value1, List<StoreProductAttrValue> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        //查询加价率
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPrice(storeProducts, merId, AreaTypeEnum.CN.getType());
        log.error("计算加价率耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        //折扣信息
        BigDecimal discountRatio = null;
        List<Integer> memberProductIdList = new ArrayList<>();
        //计算会员折扣价格
        Map<BigDecimal, List<Integer>> memberDiscountMap = priceUtil.calcMemberDiscountPrice(storeProducts, merId, false);
        if (CollectionUtils.isNotEmpty(memberDiscountMap)) {
            for (Map.Entry<BigDecimal, List<Integer>> entry : memberDiscountMap.entrySet()) {
                discountRatio = entry.getKey();
                memberProductIdList = entry.getValue();
            }
        }
        ChannelMemberLevel userMemberLevel = userService.getUserMemberLevel(userService.getInfo());
        if (userMemberLevel != null) {
            priceUtil.calcMemberLevelProductPrice(storeProducts, channelMerchant, Collections.singletonList(userMemberLevel));
        }
        log.error("计算折扣耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();



        // 渠道商户
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getMerId, merId));
        RatioVo ratioVo = priceUtil.getRatio(channelMerchant);
        List<Integer> brandIds = storeProducts.stream().map(StoreProduct::getBrandId).distinct().collect(Collectors.toList());

        List<StoreProductValueMer> productValueMerList = storeProductValueMerService.list(Wrappers.lambdaQuery(StoreProductValueMer.class).in(StoreProductValueMer::getProductId, productIds));
        Map<Integer, List<StoreProductValueMer>> merMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(productValueMerList)) {
            merMap = productValueMerList.stream().collect(Collectors.groupingBy(StoreProductValueMer::getProductId));

        }
        Map<Integer, ChannelFreeShippingActivity> productInfoMap = channelFreeShippingActivityService.getStoreProductInfoMap(productIds, merId);
        List<Integer> catIds = storeProducts.stream().map(StoreProduct::getCateId).distinct().collect(Collectors.toList());
        List<Integer> supplierIds = storeProducts.stream().map(StoreProduct::getSuppliersId).distinct().collect(Collectors.toList());

        Map<Integer, CategoryMatch> categoryMatchMap = categoryMatchService.listByIds(catIds).stream().collect(Collectors.toMap(CategoryMatch::getId, Function.identity(), (v1, v2) -> v2));
        Map<Integer, Supplier>  supplierMap= supplierService.listByIds(supplierIds).stream().collect(Collectors.toMap(Supplier::getId, Function.identity(), (v1, v2) -> v2));
        User user = userService.getInfo();
        Map<Integer, List<StoreProductRelation>> relationMap= storeProductRelationService.getLikeOrCollectByUser(user.getUid(), productIds, false).stream().collect(Collectors.groupingBy(StoreProductRelation::getProductId));
        Map<Integer, StoreBrand> brandMap = storeBrandService.listByIds(brandIds).stream().collect(Collectors.toMap(StoreBrand::getId, Function.identity(), (v1, v2) -> v2));



        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        List<StoreProductResponse> storeProductResponseList = new ArrayList<>();
        int i = 0;
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            // 查询对应属性赋值
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            if (CollectionUtils.isEmpty(values)) {
                continue;
            }
            priceUtil.calcProductValuePrice2(supplierMap, categoryMatchMap,productInfoMap, merMap, channelMerchant,  supplier, ratioVo,values, merId, product, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
            if (discountRatio != null && memberProductIdList.contains(product.getId())) {
                priceUtil.calcValueMemberDiscountPrice(values, discountRatio, channelMerchant.getAppletType());
            }
            if (userMemberLevel != null) {
                priceUtil.calcMemberLevelValuePrice(values, channelMerchant, Collections.singletonList(userMemberLevel));
            }
            Set<String> set = new LinkedHashSet<>();
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value.getAttrValue());
                    List<Object> collect = Stream.of(jsonObject.get("尺寸"), jsonObject.get("尺码"), jsonObject.get("大小"), jsonObject.get("腰带尺寸")).collect(Collectors.toList());
                    collect.removeIf(Objects::isNull);
                    set.add(collect.get(0).toString());
                } catch (Exception e) {
                    log.info("该商品无尺寸信息,商品id：{}", value.getProductId());
                }
            }
            //设置首页收藏标识
//            User user = userService.getInfo();
            if (null != user && null != user.getUid()) {
                storeProductResponse.setUserCollect(relationMap.get(id).size() > 0);
            }
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponse.setSizeList(new ArrayList<>(set));
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            // 添加品牌logo
            StoreBrand brand = brandMap.get(storeProductResponse.getBrandId());

//            StoreBrand brand = storeBrandService.getById(storeProductResponse.getBrandId());
            storeProductResponse.setBrandImage(brand.getLogo());

            storeProductResponses.add(storeProductResponse);
        }
        log.error("循环赋值计算耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);

        for (Integer id : ids) {
            if (CollectionUtils.isEmpty(storeProductResponses)) {
                continue;
            }
            storeProductResponses.stream().forEach(q -> {
                if (q.getId().equals(id)) {
                    storeProductResponseList.add(q);
                }
            });
            if (id == null) {
                storeProductResponseList.add(new StoreProductResponse());
            }
        }
        long end = System.currentTimeMillis();
        log.error("MerStoreProductServiceImpl.getFrontMerchnatList,整体耗时: {}",(end-start));

        log.info("供应商商品查询方式二新版，耗时：{}",  (end-start));
        return storeProductResponseList;
    }

    public List<StoreProductResponse> getFrontMerchantListV2(List<Integer> ids, Integer merId){
        String logKey = UUID.randomUUID().toString();
        long start = System.currentTimeMillis();
        long traceStart = System.currentTimeMillis();
        if (CollectionUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        productUtil.getChannelMerchantAuth(lambdaQueryWrapper, merId);
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        lambdaQueryWrapper.in(StoreProduct::getId, ids);
        // 查询能能显示的类目ID
        List<CategoryMatch> categoryMatchList = categoryMatchService.selectCategoryMatchDisable(merId);
        if (CollectionUtils.isNotEmpty(categoryMatchList)){
            lambdaQueryWrapper.notIn(StoreProduct::getCateId, categoryMatchList.stream().map(CategoryMatch::getId).collect(Collectors.toList()));
        }
        // 查询未上架商品
        List<StoreProductMer> storeProductMers = storeProductMerService.list(Wrappers.<StoreProductMer>lambdaQuery().select(StoreProductMer::getProductId).eq(StoreProductMer::getIsNotShow, 1));
        if (CollectionUtils.isNotEmpty(storeProductMers)){
            lambdaQueryWrapper.notIn(StoreProduct::getId, storeProductMers.stream().map(StoreProductMer::getProductId).collect(Collectors.toList()));
        }
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        log.error("查询商品数据耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();
        if (CollectionUtils.isEmpty(storeProducts)) {
            return new ArrayList<>();
        }
        // 匹配详情属性
        productConvertUtil.convertProductV2(storeProducts,merId);
        log.error("匹配详情属性耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        /******** 查询对应属性表数据(弃用循环查询, 优化搜索速度) author: daigb ********/
        List<Integer> productIds = storeProducts.stream().map(StoreProduct::getId).collect(Collectors.toList());
        // 处理attrvalue数据
        Map<Integer, List<StoreProductAttrValue>> attrValueMap = getAttrValueMap(productIds);
        //查询加价率
        Map<Integer, StoreProductMer> storeProductMerMap = priceUtil.calcProductPriceV2(storeProducts, merId, AreaTypeEnum.CN.getType());
        log.error("计算加价率耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        //折扣信息
        BigDecimal discountRatio = null;
        List<Integer> memberProductIdList = new ArrayList<>();
        //计算会员折扣价格
        Map<BigDecimal, List<Integer>> memberDiscountMap = priceUtil.calcMemberDiscountPrice(storeProducts, merId, false);
        if (CollectionUtils.isNotEmpty(memberDiscountMap)) {
            for (Map.Entry<BigDecimal, List<Integer>> entry : memberDiscountMap.entrySet()) {
                discountRatio = entry.getKey();
                memberProductIdList = entry.getValue();
            }
        }
        ChannelMerchant channelMerchant = channelMerchantService.getChannelMerchantByMerId(merId);
        ChannelMemberLevel userMemberLevel = userService.getUserMemberLevel(userService.getInfo());
        if (userMemberLevel != null) {
            priceUtil.calcMemberLevelProductPrice(storeProducts, channelMerchant, Collections.singletonList(userMemberLevel));
        }
        log.error("计算折扣耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);
        traceStart = System.currentTimeMillis();

        // 循环赋值
        List<StoreProductResponse> storeProductResponses = new ArrayList<>();
        List<StoreProductResponse> storeProductResponseList = new ArrayList<>();
        int i = 0;
        for (StoreProduct product : storeProducts) {
            Integer id = product.getId();
            StoreProductResponse storeProductResponse = new StoreProductResponse();
            BeanUtils.copyProperties(product, storeProductResponse);
            // 查询对应属性赋值
            List<StoreProductAttrValue> values = attrValueMap.get(id);
            if (CollectionUtils.isEmpty(values)) {
                continue;
            }
            priceUtil.calcProductValuePrice(values, merId, product, AreaTypeEnum.CN.getType(), storeProductMerMap, false, null, true, null);
            if (discountRatio != null && memberProductIdList.contains(product.getId())) {
                priceUtil.calcValueMemberDiscountPrice(values, discountRatio, channelMerchant.getAppletType());
            }
            if (userMemberLevel != null) {
                priceUtil.calcMemberLevelValuePrice(values, channelMerchant, Collections.singletonList(userMemberLevel));
            }
            Set<String> set = new LinkedHashSet<>();
            List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
            for (StoreProductAttrValue value : values) {
                StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
                BeanUtils.copyProperties(value, valueResponse);
                valueResponses.add(valueResponse);
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value.getAttrValue());
                    List<Object> collect = Stream.of(jsonObject.get("尺寸"), jsonObject.get("尺码"), jsonObject.get("大小"), jsonObject.get("腰带尺寸")).collect(Collectors.toList());
                    collect.removeIf(Objects::isNull);
                    set.add(collect.get(0).toString());
                } catch (Exception e) {
                    log.info("该商品无尺寸信息,商品id：{}", value.getProductId());
                }
            }
            //设置首页收藏标识
            User user = userService.getInfo();
            if (null != user && null != user.getUid()) {
                storeProductResponse.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, false).size() > 0);
            }
            storeProductResponse.setAttrValue(valueResponses);
            storeProductResponse.setSizeList(new ArrayList<>(set));
            // 通过原价算折扣率 ----处理
            if (storeProductResponse.getOtPrice() != null && storeProductResponse.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeProductResponse.getCost(), storeProductResponse.getOtPrice(), storeProductResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeProductResponse.setDiscount(bigDecimal.toString() + "折");
                }
            }
            // 添加品牌logo
            StoreBrand brand = storeBrandService.getById(storeProductResponse.getBrandId());
            storeProductResponse.setBrandImage(brand.getLogo());

            storeProductResponses.add(storeProductResponse);
        }
        log.error("循环赋值计算耗时:{},{}",(System.currentTimeMillis()-traceStart),logKey);

        for (Integer id : ids) {
            if (CollectionUtils.isEmpty(storeProductResponses)) {
                continue;
            }
            storeProductResponses.stream().forEach(q -> {
                if (q.getId().equals(id)) {
                    storeProductResponseList.add(q);
                }
            });
            if (id == null) {
                storeProductResponseList.add(new StoreProductResponse());
            }
        }
        long end = System.currentTimeMillis();
        log.error("MerStoreProductServiceImpl.getFrontMerchnatList,整体耗时: {}",(end-start));
        return storeProductResponseList;
    }

    private Map<Integer, List<StoreProductAttrValue>> getAttrValueMap(List<Integer> productIds) {
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .in(StoreProductAttrValue::getProductId, productIds)
        );
        if (CollectionUtils.isEmpty(attrValues)) {
            return new HashMap<>();
        }
        return attrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getProductId,
                s -> {
                    List<StoreProductAttrValue> list = new ArrayList<StoreProductAttrValue>();
                    list.add(s);
                    return list;
                },
                (List<StoreProductAttrValue> value1, List<StoreProductAttrValue> value2) -> {
                    value1.addAll(value2);
                    return value1;
                }
        ));
    }

//    @Override
//    public PageInfo<StoreProduct> selectProductList(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
//        queryCondition(request);
//        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
//        List<StoreProduct> list = storeProductDAO.selectProductList(request);
//        PageInfo<StoreProduct> page = new PageInfo<StoreProduct>(list);
//
//        return page;
//    }

    @Override
    public PageInfo<StoreProduct> getList(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryCondition(request, lambdaQueryWrapper);
        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
        log.info("查询语句 sqlStr:{}", sqlStr);
        // 结果查询
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = storeProductDAO.selectList(lambdaQueryWrapper);
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProductList);
        PageInfo<StoreProduct> page = new PageInfo<StoreProduct>(storeProductList);

        return page;
    }

    @Override
    public PageInfo<StoreProduct> getShopProductList(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryShopProductCondition(request, lambdaQueryWrapper);
        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);
        log.info("查询语句 sqlStr:{}", sqlStr);
        // 结果查询
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = storeProductDAO.selectList(lambdaQueryWrapper);
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProductList);
        PageInfo<StoreProduct> page = new PageInfo<StoreProduct>(storeProductList);

        return page;
    }

    @Override
    public List<StoreProduct> getListV2(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // productId过滤
        queryConditionV2(request, lambdaQueryWrapper);
        String sqlStr = MybatisPlusUtil.getSqlStr(lambdaQueryWrapper);

        // 结果查询
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = storeProductDAO.selectList(lambdaQueryWrapper);
        // 匹配详情属性
        productConvertUtil.convertProduct(storeProductList);

        return storeProductList;
    }

    // 方法弃用
	/*@Override
	public List<StoreProduct> getRecommendStoreProduct(Integer brandId, Integer limit) {
	    if (limit < 0 || limit > 20)
	        throw new CrmebException("获取推荐商品数量不合法 limit > 0 || limit < 20");
	    PageHelper.startPage(1, limit);
	    LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<StoreProduct>();
	    lambdaQueryWrapper.eq(StoreProduct::getIsGood, false);
	    if (brandId != null) {
	        lambdaQueryWrapper.eq(StoreProduct::getBrandId, brandId);
	    }
	    lambdaQueryWrapper.orderByDesc(StoreProduct::getSort).orderByDesc(StoreProduct::getId);
	    return storeProductDAO.selectList(lambdaQueryWrapper);
	}*/

    @Override
    public List<StoreProductTabsHeader> getTabsHeader(int type, Integer merId) {
        List<StoreProductTabsHeader> headers = new ArrayList<>();
        StoreProductTabsHeader header1 = new StoreProductTabsHeader(0, "出售中商品", 1);
        StoreProductTabsHeader header2 = new StoreProductTabsHeader(0, "仓库中商品", 2);
        StoreProductTabsHeader header4 = new StoreProductTabsHeader(0, "警戒库存", 4);
        StoreProductTabsHeader header5 = new StoreProductTabsHeader(0, "商品回收站", 5);
        headers.add(header1);
        headers.add(header2);
        if (1 == type) {
            StoreProductTabsHeader header3 = new StoreProductTabsHeader(0, "已经售馨商品", 3);
            headers.add(header3);
        }
        headers.add(header4);
        headers.add(header5);
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        for (StoreProductTabsHeader h : headers) {
            LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.select(StoreProduct::getId);
//            // 自建列表
//            if(1 == type) {
//                lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE);
//                lambdaQueryWrapper.eq(StoreProduct::getMerId, merId);
//            // 供应商列表
//            } else if(2 == type) {
//                List<Integer> productTypes = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
//                lambdaQueryWrapper.notIn(StoreProduct::getIsEurope, productTypes);
//            }

            List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
            List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
            List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
            if (null != brandIdsList && brandIdsList.size() > 0) {
                lambdaQueryWrapper.in(StoreProduct::getBrandId, brandIdsList);
            }
            if (null != suppliersIdList && suppliersIdList.size() > 0) {
                if (null != supplier) {
                    //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                    suppliersIdList.add(supplier.getId().toString());
                }
//            lambdaQueryWrapper.in(StoreProduct::getSuppliersId,suppliersIdList);
            }
            // 自建列表
            if (1 == type) {
                lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).eq(StoreProduct::getMerId, merId);
            } else if (2 == type) {
                //云仓 / 自建转云仓
                lambdaQueryWrapper.and(
                        e -> e.in(CollectionUtils.isNotEmpty(suppliersIdList), StoreProduct::getSuppliersId, suppliersIdList).and(
                                a -> a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                        .or(b -> b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).ne(StoreProduct::getMerId, merId).isNotNull(StoreProduct::getConvertIsEurope))
                        )
                );
//                if(null != supplier){
//                    //过滤自己自建的
//                    lambdaQueryWrapper.ne(StoreProduct::getSuppliersId,supplier.getId().toString());
//                }
            }
            if (null != tempIdList && tempIdList.size() > 0) {
                lambdaQueryWrapper.in(StoreProduct::getTempId, tempIdList);
            }

            //商户看到的商品都是平台已上架的
            if (2 == type) {
                lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
            }
            //类型搜索
            switch (h.getType()) {
                case 1:
                    //出售中（已上架）
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    if (1 == type) {
                        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                    } else {
                        //拼接下架的ids
                        lambdaQueryWrapper.notExists("SELECT 1 FROM "+ TableNameUtil.getProductMerName(merId)+" WHERE is_not_show = 1 and "
                                + TableNameUtil.getProductMerName(merId)+".product_id = eb_store_product.id");
//                        lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
                    }
                    // 库存为0的商品不显示在出售中列表
                    lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                    break;
                case 2:
                    //仓库中（未上架）
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    if (1 == type) {
                        lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                    } else {
                        //查询未下架的商品ids
//                        lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
                        lambdaQueryWrapper.exists("SELECT 1 FROM "+ TableNameUtil.getProductMerName(merId)+" WHERE is_not_show = 1 and "
                                + TableNameUtil.getProductMerName(merId)+".product_id = eb_store_product.id");
                    }
                    break;
                case 3:
                    //已售罄
                    lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    break;
                case 4:
                    //警戒库存
                    Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                    lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                    lambdaQueryWrapper.le(StoreProduct::getStock, stock);
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                    break;
                case 5:
                    //回收站
                    lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                    break;
                default:
                    break;
            }
            // lambdaQueryWrapper.orderByAsc(StoreProduct::getId);
            //过滤分类
            List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);
            Page<Object> page = PageHelper.startPage(1, 1);
            storeProductDAO.selectList(lambdaQueryWrapper);
            h.setCount(new Long(page.getTotal()).intValue());
        }

        return headers;
    }

    @Override
    public List<ProductExcelVo> getExportList(StoreProductSearchRequest request, PageParamRequest pageParamRequest, Integer merId) {
        log.info("当前的商户merId: {}", merId);
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = getQueryWrapper(request, merId);
        String sqlSegment = lambdaQueryWrapper.getSqlSegment();
        HashMap<String, Object> ew = new HashMap<String, Object>() {{
            put("paramNameValuePairs", lambdaQueryWrapper.getParamNameValuePairs());
        }};
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<ProductExcelVo> list = storeProductDAO.selectExportList(sqlSegment, ew);
        // 匹配详情属性
        productConvertUtil.convertProductExcel(list);
        for (ProductExcelVo excelVo : list) {
            //excelVo.setOtPrice(priceUtil.eur2RmbStatic(excelVo.getOtPrice(), excelVo.getExchangeRate()));
            //计算运税费加价
            StoreProduct storeProduct = new StoreProduct();
            BeanUtils.copyProperties(excelVo, storeProduct);
            StoreProductAttrValue storeProductAttrValue = new StoreProductAttrValue() {{
                setProductId(excelVo.getId());
                setPrice(excelVo.getAttrPrice());
            }};
            priceUtil.calcProductPrice(Collections.singletonList(storeProduct), merId, AreaTypeEnum.CN.getType());
            /*priceUtil.calcProductValuePrice(new ArrayList<StoreProductAttrValue>(){{
                add(storeProductAttrValue);
            }}, merId, storeProduct,AreaTypeEnum.CN.getType());*/
            excelVo.setOtPrice(storeProduct.getOtPrice());
            excelVo.setTaxAndSecondPrice(storeProduct.getTaxAndSecondPrice());
            excelVo.setPrice(storeProduct.getPrice());
            excelVo.setCost(storeProduct.getCost());
            excelVo.setCostEUR(priceUtil.rmb2EurStatic(storeProduct.getCost(), excelVo.getExchangeRate()));
            excelVo.setPriceEur(priceUtil.rmb2EurStatic(storeProduct.getPrice(), excelVo.getExchangeRate()));
            // 通过原价算折扣率 ----处理
            if (excelVo.getOtPrice() != null && excelVo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(excelVo.getPrice(), excelVo.getOtPrice(), excelVo.getExchangeRate());
                if (null != bigDecimal) {
                    excelVo.setPriceDiscount(bigDecimal.toString() + "折");
                }
            }
            //计算折扣
            if (excelVo.getOtPrice() != null && excelVo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(excelVo.getCost(), excelVo.getOtPrice(), excelVo.getExchangeRate());
                if (null == bigDecimal) {
                    excelVo.setDiscount(null);
                } else {
                    excelVo.setDiscount(bigDecimal.toString() + "折");
                }
            }
        }
        return list;
    }


    @Override
    public boolean transferCloud(Set<Integer> productIdList, Integer merId) {
        List<StoreProduct> productList = this.list(Wrappers.<StoreProduct>lambdaQuery().in(StoreProduct::getId, productIdList)
                .eq(StoreProduct::getIsEurope, 1).eq(StoreProduct::getMerId, merId)
                .select(StoreProduct::getId, StoreProduct::getSelfPushStatus, StoreProduct::getPushChangeTime, StoreProduct::getDegree));
        if (CollectionUtils.isEmpty(productList)) {
            throw new CrmebException("商品不存在");
        }
        if (productList.stream().anyMatch(e -> !Objects.equals(e.getSelfPushStatus(), 0) && !Objects.equals(e.getSelfPushStatus(), 3))) {
            throw new CrmebException("所选商品存在不是未推送/已拒绝状态的商品");
        }
        if (productList.stream().anyMatch(e -> StringUtils.isNotBlank(e.getDegree()))) {
            throw new CrmebException("所选商品存在二手商品");
        }
        for (StoreProduct storeProduct : productList) {
            storeProduct.setSelfPushStatus(1);
            storeProduct.setPushChangeTime(new Date());
        }
        return this.updateBatchById(productList);
    }

    @Override
    public List<StoreProductAttrValueResponse> openProduct(Integer productId, Integer merId) {
        StoreProduct storeProduct = this.getById(productId);
        List<StoreProductAttrValue> attrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery()
                .eq(StoreProductAttrValue::getProductId, productId)
        );
        storeProductStockService.showStockBatch(attrValues);
        priceUtil.calcProductValuePrice(attrValues, merId, storeProduct, AreaTypeEnum.CN.getType(), null, false, null, true, null);
        List<String> skuIds = attrValues.stream().map(k->String.valueOf(k.getId())).collect(Collectors.toList());
        MerPlatEnums enumByMerId = MerPlatEnums.getEnumByMerId(merId);
        List<Relation> skuRelationList = relationService.list(Wrappers.<Relation>lambdaQuery().in(Relation::getBusinessCode, skuIds)
                .eq(Relation::getBusinessType, enumByMerId == null ? MerPlatEnums.OTHER.getBusinessType().getCode():enumByMerId.getBusinessType().getCode()));
        Map<Integer, Relation> relationsMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(skuRelationList)){
            relationsMap = skuRelationList.stream().collect(Collectors.toMap(k -> Integer.valueOf(k.getBusinessCode()), v -> v));
        }
        List<StoreProductAttrValueResponse> valueResponses = new ArrayList<>();
        for (StoreProductAttrValue value : attrValues) {
            StoreProductAttrValueResponse valueResponse = new StoreProductAttrValueResponse();
            BeanUtils.copyProperties(value, valueResponse);
            if (MapUtils.isNotEmpty(relationsMap) && relationsMap.containsKey(value.getId())){
                Relation relation = relationsMap.get(value.getId());
                valueResponse.setPushPlatDesc(PlatPushStatusEnums.getDescByCode(enumByMerId == null ? MerPlatEnums.OTHER.getPlatUp().getCode():relation.getSubCode()));
            }else {
                valueResponse.setPushPlatDesc(PlatPushStatusEnums.PUSH_WAIT.getDesc());
            }
            valueResponses.add(valueResponse);
        }
        return valueResponses;
    }

    @Override
    public PageInfo<StoreProductUpload> uploadList(PageParamRequest request, Integer merId) {
        Page<Object> page = PageHelper.startPage(request.getPage(), request.getLimit());
        List<StoreProductUpload> list = storeProductUploadService.list(Wrappers.<StoreProductUpload>lambdaQuery().eq(StoreProductUpload::getSupplierId, merId).orderByDesc(StoreProductUpload::getId));
        return CommonPage.copyPageInfo(page, list);
    }

    private LambdaQueryWrapper<StoreProduct> getQueryWrapper(StoreProductSearchRequest request, Integer merId) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取渠道商户信息
        ChannelMerchant channelMerchant = channelMerchantService.getById(merId);
        if (channelMerchant == null) {
            throw new CrmebException("该商户不存在");
        }
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        if (CollectionUtils.isNotEmpty(brandIdsList)) {
            lambdaQueryWrapper.in(StoreProduct::getBrandId, brandIdsList);
        }
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            if (null != supplier) {
                //商户如果是供应商的话 查询商户自建的商品 默认传入商户配置的供应商id
                suppliersIdList.add(supplier.getId().toString());
            }
//            lambdaQueryWrapper.in(StoreProduct::getSuppliersId,suppliersIdList);
        }
        if (CollectionUtils.isNotEmpty(tempIdList)) {
            lambdaQueryWrapper.in(StoreProduct::getTempId, tempIdList);
        }

        boolean inside = ProductTypeEnum.INSIDE.getCode().equals(request.getIsEurope());
        // 自建列表
        if (inside) {
            lambdaQueryWrapper.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE).eq(StoreProduct::getMerId, merId);
            //自建商品推送状态
            if (request.getSelfPushStatus() != null) {
                lambdaQueryWrapper.eq(StoreProduct::getSelfPushStatus, request.getSelfPushStatus());
            }
        } else {
            //云仓 / 自建转云仓
            lambdaQueryWrapper.and(
                    e -> e.in(CollectionUtils.isNotEmpty(suppliersIdList), StoreProduct::getSuppliersId, suppliersIdList).and(
                            a -> a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                    .or(b -> b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                            .ne(StoreProduct::getMerId, merId)
                                            .isNotNull(StoreProduct::getConvertIsEurope))
                    )
            );
//            //云仓列表
//            if(null != supplier){
//                //过滤自己自建的
//                lambdaQueryWrapper.ne(StoreProduct::getSuppliersId,supplier.getId().toString());
//            }
        }
        //平台推荐
        if (BooleanUtil.isTrue(request.getPlatformRecommended())) {
            List<StoreZone> storeZoneList = storeZoneService.list(Wrappers.lambdaQuery(StoreZone.class).eq(StoreZone::getMerId, merId).isNotNull(StoreZone::getPushZoneId).gt(StoreZone::getEndTime, new Date()));
            List<Integer> zoneIdList = storeZoneList.stream().map(StoreZone::getId).collect(Collectors.toList());
            List<StoreZoneProduct> storeZoneProductList = CollectionUtils.isNotEmpty(zoneIdList) ? storeZoneProductService.list(
                    Wrappers.lambdaQuery(StoreZoneProduct.class)
                            .in(StoreZoneProduct::getZoneId, zoneIdList)
            ) : new ArrayList<>();

            List<Integer> recommendedProductIdList = storeZoneProductList.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            lambdaQueryWrapper.in(StoreProduct::getId, CollectionUtils.isNotEmpty(recommendedProductIdList) ? recommendedProductIdList : Arrays.asList(-1));
        }

        //关键字搜索
        if (!StringUtils.isBlank(request.getKeywords())) {
            lambdaQueryWrapper.and(i -> i
                            .or().eq(NumberUtil.isInteger(request.getKeywords()), StoreProduct::getId, request.getKeywords())
                            .or().like(StoreProduct::getKeyword, request.getKeywords())
                            .or().like(StoreProduct::getStoreName, request.getKeywords())
//                    .or().like(StoreProduct::getStoreInfo, request.getKeywords())
//                    .or().like(StoreProduct::getBarCode, request.getKeywords())
            );
        }
        if (BooleanUtil.isTrue(request.getIsBest())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_best = 1");
        }
        if (null != request.getPremiumType()) {
            if (request.getPremiumType() == 0) {
                lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE price_type != " + request.getPremiumType());
            } else {
                lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE price_type = " + request.getPremiumType());
            }
        }
        //推荐图搜索
        if (BooleanUtil.isTrue(request.getRecommendFlag())) {
            lambdaQueryWrapper.inSql(request.getRecommendFlag(), StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE recommend_img IS NOT NULL AND LENGTH(trim(recommend_img)) > 0 ");
        }
        //会员折扣商品搜索
        if (BooleanUtil.isTrue(request.getMemberDiscountFlag())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM eb_store_product_discount WHERE mer_id = " + merId);
        }
        if (request.getZoneId() != null) {
            List<StoreZoneProduct> storeZoneProduct = storeZoneProductService.list(Wrappers.<StoreZoneProduct>lambdaQuery().eq(StoreZoneProduct::getZoneId, request.getZoneId()));
            List<Integer> productIds = storeZoneProduct.stream().map(StoreZoneProduct::getProductId).distinct().collect(Collectors.toList());
            productIds.add(0);
            lambdaQueryWrapper.in(StoreProduct::getId, productIds);
        }

        //判断是否供应商筛选
        if (request.getSupplierId() != null) {
            lambdaQueryWrapper.eq(StoreProduct::getSuppliersId, request.getSupplierId());
        }
        if (CollectionUtils.isNotEmpty(request.getSupplierIds())) {
            lambdaQueryWrapper.in(StoreProduct::getSuppliersId, request.getSupplierIds());
        }

        if (CollectionUtils.isNotEmpty(request.getStockAreas())) {
            lambdaQueryWrapper.in(StoreProduct::getTempId, request.getStockAreas());
        }
        if (StringUtils.isNotBlank(request.getBrandId())) {
            lambdaQueryWrapper.eq(StoreProduct::getBrandId, request.getBrandId());
        }
        if (CollectionUtils.isNotEmpty(request.getBrandIds())) {
            lambdaQueryWrapper.in(StoreProduct::getBrandId, request.getBrandIds());
        }
        if (StringUtils.isNotBlank(request.getCateId())) {
            List<Integer> cateIds = categoryMatchService.getThreeChildVoListByPid(Integer.parseInt(request.getCateId())).stream().map(CategoryMatch::getId).collect(Collectors.toList());
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }
        if (CollectionUtils.isNotEmpty(request.getCateIds())) {
            List<Integer> cateIds = new ArrayList<>();
            request.getCateIds().forEach(cateId -> cateIds.addAll(categoryMatchService.getThreeChildVoListByPid(cateId).stream().map(CategoryMatch::getId).collect(Collectors.toList())));
            String cateIdStr = StringUtils.join(cateIds, ",");
            lambdaQueryWrapper.apply(CrmebUtil.getFindInSetSql("cate_id", cateIdStr));
        }

        // 最大小库存
        if (request.getMinStock() != null && request.getMaxStock() == null) {
            lambdaQueryWrapper.ge(StoreProduct::getStock, request.getMinStock());
        } else if (request.getMinStock() == null && request.getMaxStock() != null) {
            lambdaQueryWrapper.le(StoreProduct::getStock, request.getMaxStock());
        } else if (request.getMinStock() != null && request.getMaxStock() != null) {
            lambdaQueryWrapper.between(StoreProduct::getStock, request.getMinStock(), request.getMaxStock());
        }
        if (null != request.getSeasonCode()) {
            if ("-1".equals(request.getSeasonCode())) {
                lambdaQueryWrapper.isNull(StoreProduct::getSeasonCode);
            } else {
                lambdaQueryWrapper.likeRight(StoreProduct::getSeasonCode, request.getSeasonCode());
            }
        }

        if (!inside) {
            //商户看到的云仓商品都是平台已上架的
            lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        }
        //类型搜索
        switch (request.getType()) {
            case 1:
                //出售中（已上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                if (inside) {
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
                } else {
                    //查询下架的商品ids  警示语句，不能使用in ，not in等子语句
//                    lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
                    lambdaQueryWrapper.notExists("SELECT 1 FROM "+ TableNameUtil.getProductMerName(merId)+" WHERE is_not_show = 1 and "
                            + TableNameUtil.getProductMerName(merId)+".product_id = eb_store_product.id");

                }
                // 库存为0的商品不显示在出售中列表
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                break;
            case 2:
                //仓库中（未上架）
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                if (inside) {
                    lambdaQueryWrapper.eq(StoreProduct::getIsShow, false);
                } else {
                    //查询下架的商品ids  警示语句，不能使用in ，not in等子语句
//                    lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
                    lambdaQueryWrapper.exists("SELECT 1 FROM "+ TableNameUtil.getProductMerName(merId)+" WHERE is_not_show = 1 and "
                            + TableNameUtil.getProductMerName(merId)+".product_id = eb_store_product.id");
                }
                break;
            case 3:
                //已售罄
                lambdaQueryWrapper.le(StoreProduct::getStock, 0);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 4:
                //警戒库存
                //Integer stock = Integer.parseInt(systemConfigService.getValueByKey("store_stock"));
                lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
                lambdaQueryWrapper.le(StoreProduct::getStock, 2);
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
                break;
            case 5:
                //回收站
                lambdaQueryWrapper.eq(StoreProduct::getIsDel, true);
                break;
            default:
                break;
        }
        //自建商品二手/新品查询
        if (Objects.equals(ProductTypeEnum.INSIDE.getCode(), request.getIsEurope())) {
            if (Objects.equals(1, request.getOrderType())) {
                lambdaQueryWrapper.and(i -> i.or().isNull(StoreProduct::getDegree).or().eq(StoreProduct::getDegree, ""));
            }
            if (Objects.equals(3, request.getOrderType())) {
                lambdaQueryWrapper.isNotNull(StoreProduct::getDegree).ne(StoreProduct::getDegree, "");
            }
        }
        if (CollectionUtils.isNotEmpty(request.getPickingIds())) {
            //查sku存在的商品
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT DISTINCT v.product_id FROM eb_store_product_picking p LEFT JOIN eb_store_product_attr_value v on p.sku_id = v.source_sku_id where p.picking_id in " + request.getPickingIds().toString().replace("[", "(").replace("]", ")"));
//            lambdaQueryWrapper.inSql(StoreProduct::getId,"SELECT DISTINCT product_id FROM eb_store_product_picking WHERE picking_id in "+request.getPickingIds().toString().replace("[","(").replace("]",")"));
        }
        if (CollectionUtils.isNotEmpty(request.getActivityIds())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT DISTINCT a.product_id FROM eb_store_product_activity a LEFT JOIN eb_store_product b on a.product_id = b.id where a.activity_id in " + request.getActivityIds().toString().replace("[", "(").replace("]", ")"));
        }
        if (request.isSellingBelowCost()) {
            lambdaQueryWrapper.apply(" price < cost ");
        }
        if (StringUtils.isNotBlank(request.getLabelName())) {
            lambdaQueryWrapper.inSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE label_id IN ( SELECT spl.id  FROM eb_store_product_label spl WHERE spl.label_name LIKE '%" + request.getLabelName() + "%' )");
        }
        //过滤分类
        List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);

        if (StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimit = DateUtil.getDateLimit(request.getDateLimit());
            lambdaQueryWrapper.between(StoreProduct::getCreateTime, dateLimit.getStartTime(), dateLimit.getEndTime());
        }

        MarkupRateRequest rateRequest = new MarkupRateRequest();
        rateRequest.setMerId(merId);
        rateRequest.setType(MarkupRateTypeEnum.PLAT_平台加价率.getType());
        BigDecimal platRatio = markupRateService.selectMerchantRatio(rateRequest);
        rateRequest.setType(MarkupRateTypeEnum.MERCHANT_商户加价率.getType());
        BigDecimal merRatio = markupRateService.selectMerchantRatio(rateRequest);
        //价格筛选
        if (request.getMinPrice() != null || request.getMaxPrice() != null) {
            if (request.getMinPrice() != null && request.getMaxPrice() == null) {
                lambdaQueryWrapper.ge(StoreProduct::getPrice, UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMinPrice()), platRatio, merRatio));
            } else if (request.getMinPrice() == null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.le(StoreProduct::getPrice, UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMaxPrice()), platRatio, merRatio));
            } else if (request.getMinPrice() != null && request.getMaxPrice() != null) {
                lambdaQueryWrapper.between(StoreProduct::getPrice, UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMinPrice()), platRatio, merRatio)
                        , UnitConvertUtil.getInitialPrice(new BigDecimal(request.getMaxPrice()), platRatio, merRatio));
            }
        }
        //折扣价查询条件
        RatioVo ratioVo = priceUtil.getRatio(channelMerchant);
        BigDecimal multiply = (ratioVo.getPlatRatio().movePointLeft(2).add(BigDecimal.ONE));
        StringBuilder ratio = new StringBuilder();
        ratio.append(" (CASE when is_europe = 1 then 1 ELSE ").append(multiply).append(" end) ");
        StringBuilder str = new StringBuilder();
        if (request.getMinDiscount() != null || request.getMaxDiscount() != null || request.getCostSort() != null) {
            //头程
            str.append(" (CASE when is_europe = 1 then 0 ELSE ");
            str.append(" (CASE when is_europe = 29 then 20 when is_europe = 31 and temp_id =1 then 20 when temp_id <> 1 and left(suppliers_name,2)=\"HK\" then 30");
            str.append(" ELSE  0 end) end)");
        }
        BigDecimal agentRatio = BigDecimal.ONE;
        if (ratioVo.getFirstAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getFirstAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        if (ratioVo.getSecondAgentRatio() != null) {
            agentRatio = agentRatio.multiply(ratioVo.getSecondAgentRatio().movePointLeft(2).add(BigDecimal.ONE));
        }
        if (request.getMinDiscount() != null && request.getMaxDiscount() == null) {
            lambdaQueryWrapper.apply("CEILING( (cost * " + ratio + " + " + str + " ) * " + agentRatio + " / (ot_price * exchange_rate)*100) / 10 >= {0} ", request.getMinDiscount());
        } else if (request.getMinDiscount() == null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("CEILING( (cost * " + ratio + " + " + str + " ) * " + agentRatio + " / (ot_price * exchange_rate)*100) / 10 <= {0} ", request.getMaxDiscount());
        } else if (request.getMinDiscount() != null && request.getMaxDiscount() != null) {
            lambdaQueryWrapper.apply("CEILING( (cost * " + ratio + " + " + str + " ) * " + agentRatio + " / (ot_price * exchange_rate)*100) / 10 BETWEEN  {0} and {1} ", request.getMinDiscount(), request.getMaxDiscount());
        }
//        lambdaQueryWrapper.orderByDesc(StoreProduct::getId);

        // 成本价折扣排序
        if (request.getCostSort() != null) {
            String value = request.getCostSort() == 0 ? "ASC" : "DESC";
            lambdaQueryWrapper.last(" ORDER BY CEILING( (cost * " + ratio + " + " + str + " ) * " + agentRatio + " / (ot_price * exchange_rate)*100) / 10 " + value);
        } else {
            lambdaQueryWrapper.orderByDesc(StoreProduct::getLastPushTime);
        }
        // 商品推送状态筛选
        if (CollectionUtils.isNotEmpty(request.getProductPushStatusList())){
            String pushStatus = request.getProductPushStatusList().get(0);
            String businessType = getBusinessType(pushStatus);
            String sqlStr = "SELECT 1 FROM eb_relation WHERE eb_relation.business_code = eb_store_product.id and sub_code = '"+pushStatus+"'";
            if (StringUtils.isNotBlank(businessType)){
                sqlStr = sqlStr + " and business_type = '"+businessType+"'";
            }
            lambdaQueryWrapper.exists(sqlStr);
        }
        return lambdaQueryWrapper;
    }

    private String getBusinessType(String pushStatus) {
        if (StringUtils.isBlank(pushStatus)){
            return "";
        }
        String[] split = pushStatus.split("_");
        if (split.length<2){
            return "";
        }
        String prefix = split[0];
        String codeByPrefix = BusinessTypeEnums.getCodeByPrefix(prefix);
        if (StringUtils.isBlank(codeByPrefix)){
            return "";
        }
        return codeByPrefix;

    }

    /**
     * @param productId 商品id
     * @return
     */
    @Override
    public Boolean deleteProduct(Integer productId) {
        LambdaUpdateWrapper<StoreProduct> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(StoreProduct::getId, productId);
        lambdaUpdateWrapper.set(StoreProduct::getIsDel, true);
        lambdaUpdateWrapper.set(StoreProduct::getIsEurope, 1);
        return update(lambdaUpdateWrapper);
    }

    @Override
    public List<ProductExcelVo> getStoreCartProductByUid(Integer uid) {
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 用户购物车数据
        List<StoreCart> storeCarts = storeCartService.list(Wrappers.<StoreCart>lambdaQuery().eq(StoreCart::getUid, uid).eq(StoreCart::getType, "product").eq(StoreCart::getIsNew, 0));
        if (CollectionUtils.isEmpty(storeCarts)) {
            return new ArrayList<>();
        }
        // 购物车中商品id
        List<Integer> productIds = storeCarts.stream().map(StoreCart::getProductId).collect(Collectors.toList());
        List<String> attrValueIds = storeCarts.stream().map(StoreCart::getProductAttrUnique).collect(Collectors.toList());
        lambdaQueryWrapper.in(StoreProduct::getId, productIds);
        String sqlSegment = lambdaQueryWrapper.getSqlSegment();
        HashMap<String, Object> ew = new HashMap<String, Object>() {{
            put("paramNameValuePairs", lambdaQueryWrapper.getParamNameValuePairs());
        }};
        List<ProductExcelVo> list = storeProductDAO.selectExportList1(sqlSegment, ew, attrValueIds);
        productConvertUtil.convertProductExcel(list);
        for (ProductExcelVo excelVo : list) {
            //excelVo.setOtPrice(priceUtil.eur2RmbStatic(excelVo.getOtPrice(), excelVo.getExchangeRate()));
            //计算运税费加价
            StoreProduct storeProduct = new StoreProduct();
            BeanUtils.copyProperties(excelVo, storeProduct);
            StoreProductAttrValue storeProductAttrValue = new StoreProductAttrValue() {{
                setProductId(excelVo.getId());
                setPrice(excelVo.getAttrPrice());
            }};
            priceUtil.calcProductPrice(Collections.singletonList(storeProduct), 18, AreaTypeEnum.CN.getType());
            /*priceUtil.calcProductValuePrice(new ArrayList<StoreProductAttrValue>(){{
                add(storeProductAttrValue);
            }}, merId, storeProduct,AreaTypeEnum.CN.getType());*/
            excelVo.setAttrOtPrice(storeProduct.getOtPrice());
            excelVo.setTaxAndSecondPrice(storeProduct.getTaxAndSecondPrice());
            excelVo.setAttrPrice(storeProduct.getPrice());
            excelVo.setAttrCost(storeProduct.getCost());
            excelVo.setCostEUR(priceUtil.rmb2EurStatic(storeProduct.getCost(), excelVo.getExchangeRate()));
            excelVo.setPriceEur(priceUtil.rmb2EurStatic(storeProduct.getPrice(), excelVo.getExchangeRate()));
            // 通过原价算折扣率 ----处理
            if (excelVo.getOtPrice() != null && excelVo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(excelVo.getPrice(), excelVo.getOtPrice(), excelVo.getExchangeRate());
                if (null != bigDecimal) {
                    excelVo.setPriceDiscount(bigDecimal.toString() + "折");
                }
            }
            //计算折扣
            if (excelVo.getOtPrice() != null && excelVo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(excelVo.getCost(), excelVo.getOtPrice(), excelVo.getExchangeRate());
                if (null == bigDecimal) {
                    excelVo.setDiscount(null);
                } else {
                    excelVo.setDiscount(bigDecimal.toString() + "折");
                }
            }
        }
        return list;
    }

    @Override
    public List<String> getProductNameByKeywords(String keywords, Integer merId) {
        IndexStoreProductSearchRequest request = new IndexStoreProductSearchRequest();
        List<String> storeNames = new ArrayList<>();
        request.setType(1);
        request.setIsShow(1);
        request.setMerId(merId);
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        queryCondition(request, lambdaQueryWrapper);
        // 只查询商品名称
        lambdaQueryWrapper.select(StoreProduct::getStoreName);
        // 左匹配商品关键字
        lambdaQueryWrapper.likeRight(StoreProduct::getStoreName, keywords);
        lambdaQueryWrapper.groupBy(StoreProduct::getStoreName);
        // 限制10条
        lambdaQueryWrapper.last("limit 10");
        List<StoreProduct> storeProducts = storeProductDAO.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(storeProducts)) {
            return storeNames;
        }
        storeNames = storeProducts.stream().map(StoreProduct::getStoreName).sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList());

        return storeNames;
    }

}
